#!/usr/bin/env python3
"""
SnapSell AI Logo Generator
Generates horizontal and stacked logo variants with research-backed typography spacing.
"""

from PIL import Image, ImageDraw, ImageFont
from pathlib import Path
import subprocess
import os

# Configuration based on research-backed typography guidelines
HORIZONTAL_CONFIG = {
    "icon_height": 580,
    "name_font_size": 320,
    "claim_font_size": 140,
    "gap_icon_to_text": 80,
    "gap_name_to_claim": 100,
    "padding": 100,
    "optical_offset": 50,
}

STACKED_CONFIG = {
    "icon_height": 350,
    "name_font_size": 120,
    "claim_font_size": 42,
    "gap_icon_to_name": 80,
    "gap_name_to_claim": 50,
    "padding": 60,
}

# Brand details
BRAND_NAME = "SNAPSELL AI"
CLAIM = "Snap. List. Sell."

# Colors
TEXT_DARK = "#1F2937"
TEXT_WHITE = "#FFFFFF"
TEXT_BLACK = "#000000"

# Font paths - try multiple locations
FONT_PATHS = [
    "/System/Library/Fonts/Supplemental/Impact.ttf",
    "/System/Library/Fonts/Helvetica.ttc",
    "/Library/Fonts/Arial.ttf",
    "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
]

CLAIM_FONT_PATHS = [
    "/System/Library/Fonts/Helvetica.ttc",
    "/Library/Fonts/Arial.ttf",
    "/System/Library/Fonts/Supplemental/Arial.ttf",
]


def get_font(size, bold=False):
    """Get a font, trying multiple paths."""
    for path in FONT_PATHS:
        try:
            return ImageFont.truetype(path, size)
        except (OSError, IOError):
            continue
    return ImageFont.load_default()


def get_claim_font(size):
    """Get a font for the claim text."""
    for path in CLAIM_FONT_PATHS:
        try:
            return ImageFont.truetype(path, size)
        except (OSError, IOError):
            continue
    return ImageFont.load_default()


def load_icon(icon_path, target_height):
    """Load and resize icon to target height."""
    icon = Image.open(icon_path).convert("RGBA")
    aspect = icon.width / icon.height
    new_width = int(target_height * aspect)
    return icon.resize((new_width, target_height), Image.Resampling.LANCZOS)


def create_horizontal_logo(icon_path, output_path, text_color, with_claim=False):
    """Create horizontal logo (icon + name side by side)."""
    cfg = HORIZONTAL_CONFIG

    # Load icon
    icon = load_icon(icon_path, cfg["icon_height"])

    # Create fonts
    name_font = get_font(cfg["name_font_size"])
    claim_font = get_claim_font(cfg["claim_font_size"])

    # Calculate text sizes
    dummy_img = Image.new("RGBA", (1, 1))
    draw = ImageDraw.Draw(dummy_img)

    name_bbox = draw.textbbox((0, 0), BRAND_NAME, font=name_font)
    name_width = name_bbox[2] - name_bbox[0]
    name_height = name_bbox[3] - name_bbox[1]

    claim_width, claim_height = 0, 0
    if with_claim:
        claim_bbox = draw.textbbox((0, 0), CLAIM, font=claim_font)
        claim_width = claim_bbox[2] - claim_bbox[0]
        claim_height = claim_bbox[3] - claim_bbox[1]

    # Calculate canvas size
    text_block_width = max(name_width, claim_width if with_claim else 0)
    text_block_height = name_height + (cfg["gap_name_to_claim"] + claim_height if with_claim else 0)

    canvas_width = cfg["padding"] + icon.width + cfg["gap_icon_to_text"] + text_block_width + cfg["padding"]
    canvas_height = cfg["padding"] * 2 + max(icon.height, text_block_height)

    # Create canvas
    canvas = Image.new("RGBA", (canvas_width, canvas_height), (255, 255, 255, 0))

    # Position icon (vertically centered)
    icon_x = cfg["padding"]
    icon_y = (canvas_height - icon.height) // 2
    canvas.paste(icon, (icon_x, icon_y), icon)

    # Position text
    text_x = cfg["padding"] + icon.width + cfg["gap_icon_to_text"]
    text_y = (canvas_height - text_block_height) // 2 + cfg["optical_offset"]

    # Draw text
    draw = ImageDraw.Draw(canvas)
    draw.text((text_x, text_y), BRAND_NAME, font=name_font, fill=text_color)

    if with_claim:
        claim_y = text_y + name_height + cfg["gap_name_to_claim"]
        draw.text((text_x, claim_y), CLAIM, font=claim_font, fill=text_color)

    # Save
    canvas.save(output_path, "PNG")
    print(f"Created: {output_path}")
    return canvas.size


def create_stacked_logo(icon_path, output_path, text_color, with_claim=False):
    """Create stacked logo (icon above name)."""
    cfg = STACKED_CONFIG

    # Load icon
    icon = load_icon(icon_path, cfg["icon_height"])

    # Create fonts
    name_font = get_font(cfg["name_font_size"])
    claim_font = get_claim_font(cfg["claim_font_size"])

    # Calculate text sizes
    dummy_img = Image.new("RGBA", (1, 1))
    draw = ImageDraw.Draw(dummy_img)

    name_bbox = draw.textbbox((0, 0), BRAND_NAME, font=name_font)
    name_width = name_bbox[2] - name_bbox[0]
    name_height = name_bbox[3] - name_bbox[1]

    claim_width, claim_height = 0, 0
    if with_claim:
        claim_bbox = draw.textbbox((0, 0), CLAIM, font=claim_font)
        claim_width = claim_bbox[2] - claim_bbox[0]
        claim_height = claim_bbox[3] - claim_bbox[1]

    # Calculate canvas size
    content_width = max(icon.width, name_width, claim_width if with_claim else 0)
    content_height = icon.height + cfg["gap_icon_to_name"] + name_height
    if with_claim:
        content_height += cfg["gap_name_to_claim"] + claim_height

    canvas_width = cfg["padding"] * 2 + content_width
    canvas_height = cfg["padding"] * 2 + content_height

    # Create canvas
    canvas = Image.new("RGBA", (canvas_width, canvas_height), (255, 255, 255, 0))

    # Position icon (horizontally centered)
    icon_x = (canvas_width - icon.width) // 2
    icon_y = cfg["padding"]
    canvas.paste(icon, (icon_x, icon_y), icon)

    # Position name (horizontally centered)
    name_x = (canvas_width - name_width) // 2
    name_y = icon_y + icon.height + cfg["gap_icon_to_name"]

    # Draw text
    draw = ImageDraw.Draw(canvas)
    draw.text((name_x, name_y), BRAND_NAME, font=name_font, fill=text_color)

    if with_claim:
        claim_x = (canvas_width - claim_width) // 2
        claim_y = name_y + name_height + cfg["gap_name_to_claim"]
        draw.text((claim_x, claim_y), CLAIM, font=claim_font, fill=text_color)

    # Save
    canvas.save(output_path, "PNG")
    print(f"Created: {output_path}")
    return canvas.size


def main():
    base_dir = Path(__file__).parent / "logos"

    # Icon paths
    icons = {
        "colorful": base_dir / "icon_colorful_1024.png",
        "white": base_dir / "icon_white_1024.png",
        "black": base_dir / "icon_black_1024.png",
    }

    # Text colors for each variant
    text_colors = {
        "colorful": TEXT_DARK,
        "white": TEXT_WHITE,
        "black": TEXT_BLACK,
    }

    # Generate all variants
    for variant, icon_path in icons.items():
        text_color = text_colors[variant]

        # Horizontal without claim
        create_horizontal_logo(
            icon_path,
            base_dir / f"logo_horizontal_{variant}.png",
            text_color,
            with_claim=False
        )

        # Horizontal with claim
        create_horizontal_logo(
            icon_path,
            base_dir / f"logo_horizontal_claim_{variant}.png",
            text_color,
            with_claim=True
        )

        # Stacked without claim
        create_stacked_logo(
            icon_path,
            base_dir / f"logo_stacked_{variant}.png",
            text_color,
            with_claim=False
        )

        # Stacked with claim
        create_stacked_logo(
            icon_path,
            base_dir / f"logo_stacked_claim_{variant}.png",
            text_color,
            with_claim=True
        )

    print("\nAll logo variants generated!")


if __name__ == "__main__":
    main()
