#!/usr/bin/env python3
"""
HabitTracker 2026 App Store Screenshots Generator
Creates professional marketing screenshots for App Store submission
"""

from PIL import Image, ImageDraw, ImageFont, ImageFilter
import math
import os

# App Store screenshot sizes
SIZES = {
    "6.7": (1290, 2796),  # iPhone 15 Pro Max
    "6.5": (1242, 2688),  # iPhone 11 Pro Max
    "5.5": (1242, 2208),  # iPhone 8 Plus
}

# Use 6.7" as primary
WIDTH, HEIGHT = SIZES["6.7"]

# Colors matching app theme
COLORS = {
    "purple_dark": (88, 28, 135),
    "purple": (124, 58, 237),
    "blue": (59, 130, 246),
    "teal": (20, 184, 166),
    "white": (255, 255, 255),
    "red": (239, 68, 68),
    "orange": (249, 115, 22),
    "green": (34, 197, 94),
    "gray": (156, 163, 175),
}

def create_gradient_background(width, height):
    """Create mesh gradient background"""
    img = Image.new('RGB', (width, height))

    for y in range(height):
        for x in range(width):
            fx = x / width
            fy = y / height

            # Diagonal gradient with wave
            wave = math.sin(fx * math.pi) * 0.15
            factor = (fx * 0.3 + fy * 0.7 + wave)
            factor = max(0, min(1, factor))

            c1 = COLORS["purple_dark"]
            c2 = COLORS["blue"]

            r = int(c1[0] + (c2[0] - c1[0]) * factor)
            g = int(c1[1] + (c2[1] - c1[1]) * factor)
            b = int(c1[2] + (c2[2] - c1[2]) * factor)

            img.putpixel((x, y), (r, g, b))

    return img

def draw_rounded_rect(draw, coords, radius, fill):
    """Draw a rounded rectangle"""
    x1, y1, x2, y2 = coords

    # Main rectangle
    draw.rectangle([x1 + radius, y1, x2 - radius, y2], fill=fill)
    draw.rectangle([x1, y1 + radius, x2, y2 - radius], fill=fill)

    # Corners
    draw.ellipse([x1, y1, x1 + radius * 2, y1 + radius * 2], fill=fill)
    draw.ellipse([x2 - radius * 2, y1, x2, y1 + radius * 2], fill=fill)
    draw.ellipse([x1, y2 - radius * 2, x1 + radius * 2, y2], fill=fill)
    draw.ellipse([x2 - radius * 2, y2 - radius * 2, x2, y2], fill=fill)

def draw_glass_card(img, coords, alpha=180):
    """Draw a glass morphism card"""
    x1, y1, x2, y2 = coords
    radius = 40

    # Create overlay
    overlay = Image.new('RGBA', img.size, (0, 0, 0, 0))
    draw = ImageDraw.Draw(overlay)

    # Semi-transparent background
    draw_rounded_rect(draw, coords, radius, (255, 255, 255, alpha))

    # Composite
    img_rgba = img.convert('RGBA')
    return Image.alpha_composite(img_rgba, overlay)

def draw_habit_row(draw, y, emoji, name, streak, completed, color, width):
    """Draw a habit row"""
    padding = 60
    card_height = 120

    # Card background (glass effect simulated with lighter color)
    x1, y1 = padding, y
    x2, y2 = width - padding, y + card_height
    draw_rounded_rect(draw, (x1, y1, x2, y2), 25, (255, 255, 255, 40))

    # Emoji circle
    emoji_x = x1 + 70
    emoji_y = y + card_height // 2
    draw.ellipse([emoji_x - 35, emoji_y - 35, emoji_x + 35, emoji_y + 35],
                 fill=(*color, 60))

    # Habit name
    try:
        font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 36)
        small_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 24)
    except:
        font = ImageFont.load_default()
        small_font = font

    draw.text((emoji_x + 60, emoji_y - 25), name, fill=COLORS["white"], font=font)

    # Streak
    if streak > 0:
        draw.text((emoji_x + 60, emoji_y + 10), f"🔥 {streak} dias",
                  fill=COLORS["orange"], font=small_font)

    # Checkmark circle
    check_x = x2 - 70
    check_y = emoji_y
    circle_color = color if completed else (255, 255, 255, 80)
    draw.ellipse([check_x - 25, check_y - 25, check_x + 25, check_y + 25],
                 outline=circle_color, width=4)
    if completed:
        draw.ellipse([check_x - 18, check_y - 18, check_x + 18, check_y + 18],
                     fill=color)

def create_screenshot_1():
    """Welcome/Onboarding Screenshot"""
    img = create_gradient_background(WIDTH, HEIGHT)
    draw = ImageDraw.Draw(img)

    # Marketing text at top
    try:
        title_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 72)
        subtitle_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 42)
    except:
        title_font = ImageFont.load_default()
        subtitle_font = title_font

    # Title
    title = "Transforme sua vida"
    title_bbox = draw.textbbox((0, 0), title, font=title_font)
    title_w = title_bbox[2] - title_bbox[0]
    draw.text(((WIDTH - title_w) // 2, 180), title, fill=COLORS["white"], font=title_font)

    subtitle = "em 2026"
    sub_bbox = draw.textbbox((0, 0), subtitle, font=title_font)
    sub_w = sub_bbox[2] - sub_bbox[0]
    draw.text(((WIDTH - sub_w) // 2, 270), subtitle, fill=COLORS["teal"], font=title_font)

    # Large target emoji
    target_y = HEIGHT // 2 - 100

    # Draw target
    center_x = WIDTH // 2
    rings = [
        (200, COLORS["white"]),
        (160, COLORS["red"]),
        (120, COLORS["white"]),
        (80, COLORS["red"]),
        (40, COLORS["white"]),
        (20, COLORS["red"]),
    ]

    for radius, color in rings:
        draw.ellipse([center_x - radius, target_y - radius,
                      center_x + radius, target_y + radius], fill=color)

    # Feature bullets
    features = [
        "✓ Acompanhe seus hábitos diários",
        "✓ Mantenha streaks motivacionais",
        "✓ Sincronize com iCloud",
        "✓ Design moderno Liquid Glass"
    ]

    feature_y = target_y + 300
    for feature in features:
        feat_bbox = draw.textbbox((0, 0), feature, font=subtitle_font)
        feat_w = feat_bbox[2] - feat_bbox[0]
        draw.text(((WIDTH - feat_w) // 2, feature_y), feature,
                  fill=COLORS["white"], font=subtitle_font)
        feature_y += 70

    return img

def create_screenshot_2():
    """Home Screen with Habits"""
    img = create_gradient_background(WIDTH, HEIGHT)
    draw = ImageDraw.Draw(img)

    try:
        title_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 72)
        header_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 48)
        body_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 36)
    except:
        title_font = header_font = body_font = ImageFont.load_default()

    # Marketing text
    title = "Todos seus hábitos"
    title_bbox = draw.textbbox((0, 0), title, font=title_font)
    title_w = title_bbox[2] - title_bbox[0]
    draw.text(((WIDTH - title_w) // 2, 150), title, fill=COLORS["white"], font=title_font)

    subtitle = "em um só lugar"
    sub_bbox = draw.textbbox((0, 0), subtitle, font=header_font)
    sub_w = sub_bbox[2] - sub_bbox[0]
    draw.text(((WIDTH - sub_w) // 2, 240), subtitle, fill=COLORS["gray"], font=header_font)

    # Mockup phone screen area
    phone_y = 400

    # Today's summary card
    card_x1, card_y1 = 80, phone_y
    card_x2, card_y2 = WIDTH - 80, phone_y + 200
    draw_rounded_rect(draw, (card_x1, card_y1, card_x2, card_y2), 30, (255, 255, 255, 30))

    draw.text((card_x1 + 40, card_y1 + 30), "Hoje", fill=COLORS["gray"], font=body_font)
    draw.text((card_x1 + 40, card_y1 + 80), "5/6", fill=COLORS["white"], font=title_font)
    draw.text((card_x1 + 180, card_y1 + 110), "hábitos", fill=COLORS["gray"], font=body_font)

    # Progress circle
    circle_x = card_x2 - 150
    circle_y = card_y1 + 100
    draw.arc([circle_x - 60, circle_y - 60, circle_x + 60, circle_y + 60],
             0, 360, fill=(255, 255, 255, 50), width=12)
    draw.arc([circle_x - 60, circle_y - 60, circle_x + 60, circle_y + 60],
             -90, 210, fill=COLORS["green"], width=12)
    draw.text((circle_x - 30, circle_y - 20), "83%", fill=COLORS["white"], font=body_font)

    # Streak badge
    draw.text((card_x2 - 100, card_y1 + 30), "🔥 12", fill=COLORS["orange"], font=header_font)

    # Habit rows
    habits = [
        ("🧘", "Meditar 10 min", 12, True, COLORS["purple"]),
        ("💪", "Exercício", 8, True, COLORS["red"]),
        ("📚", "Ler 30 páginas", 5, True, COLORS["blue"]),
        ("💧", "Beber 2L água", 15, True, COLORS["teal"]),
        ("✍️", "Journaling", 3, False, COLORS["orange"]),
        ("🌅", "Acordar 6h", 7, True, COLORS["green"]),
    ]

    habit_y = card_y2 + 40
    for emoji, name, streak, completed, color in habits:
        draw_habit_row(draw, habit_y, emoji, name, streak, completed, color, WIDTH)
        habit_y += 140

    return img

def create_screenshot_3():
    """Streak/Stats Screenshot"""
    img = create_gradient_background(WIDTH, HEIGHT)
    draw = ImageDraw.Draw(img)

    try:
        title_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 72)
        big_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 120)
        body_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 36)
    except:
        title_font = big_font = body_font = ImageFont.load_default()

    # Title
    title = "Mantenha o foco"
    title_bbox = draw.textbbox((0, 0), title, font=title_font)
    title_w = title_bbox[2] - title_bbox[0]
    draw.text(((WIDTH - title_w) // 2, 150), title, fill=COLORS["white"], font=title_font)

    subtitle = "com streaks diários"
    sub_bbox = draw.textbbox((0, 0), subtitle, font=body_font)
    sub_w = sub_bbox[2] - sub_bbox[0]
    draw.text(((WIDTH - sub_w) // 2, 250), subtitle, fill=COLORS["gray"], font=body_font)

    # Big streak number
    streak_y = 500
    draw.text((WIDTH // 2 - 150, streak_y), "🔥", font=big_font)
    draw.text((WIDTH // 2 + 50, streak_y), "45", fill=COLORS["orange"], font=big_font)
    draw.text((WIDTH // 2 - 80, streak_y + 180), "dias consecutivos",
              fill=COLORS["white"], font=body_font)

    # Stats cards
    stats = [
        ("Taxa de conclusão", "87%", COLORS["green"]),
        ("Hábitos ativos", "6", COLORS["blue"]),
        ("Melhor streak", "45", COLORS["orange"]),
    ]

    card_y = 900
    card_width = (WIDTH - 160 - 40) // 3

    for i, (label, value, color) in enumerate(stats):
        x = 80 + i * (card_width + 20)
        draw_rounded_rect(draw, (x, card_y, x + card_width, card_y + 200), 20, (255, 255, 255, 30))

        # Value
        val_bbox = draw.textbbox((0, 0), value, font=title_font)
        val_w = val_bbox[2] - val_bbox[0]
        draw.text((x + (card_width - val_w) // 2, card_y + 40), value, fill=color, font=title_font)

        # Label (smaller, centered)
        try:
            small_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 24)
        except:
            small_font = body_font
        lab_bbox = draw.textbbox((0, 0), label, font=small_font)
        lab_w = lab_bbox[2] - lab_bbox[0]
        draw.text((x + (card_width - lab_w) // 2, card_y + 140), label,
                  fill=COLORS["gray"], font=small_font)

    # Weekly chart mockup
    chart_y = 1200
    draw_rounded_rect(draw, (80, chart_y, WIDTH - 80, chart_y + 350), 30, (255, 255, 255, 20))

    draw.text((120, chart_y + 30), "Última semana", fill=COLORS["white"], font=body_font)

    # Bar chart
    days = ["S", "T", "Q", "Q", "S", "S", "D"]
    values = [0.6, 0.8, 1.0, 0.7, 0.9, 1.0, 0.8]
    bar_width = 80
    max_height = 180
    start_x = 140
    bar_y = chart_y + 280

    for i, (day, val) in enumerate(zip(days, values)):
        x = start_x + i * (bar_width + 30)
        height = int(val * max_height)

        # Bar
        draw_rounded_rect(draw, (x, bar_y - height, x + bar_width, bar_y), 10, COLORS["teal"])

        # Day label
        draw.text((x + 25, bar_y + 10), day, fill=COLORS["gray"], font=body_font)

    # Bottom tagline
    tagline = "Nunca quebre a corrente 💪"
    tag_bbox = draw.textbbox((0, 0), tagline, font=body_font)
    tag_w = tag_bbox[2] - tag_bbox[0]
    draw.text(((WIDTH - tag_w) // 2, HEIGHT - 200), tagline, fill=COLORS["white"], font=body_font)

    return img

def create_screenshot_4():
    """Add Habit Screenshot"""
    img = create_gradient_background(WIDTH, HEIGHT)
    draw = ImageDraw.Draw(img)

    try:
        title_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 72)
        body_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 36)
    except:
        title_font = body_font = ImageFont.load_default()

    # Title
    title = "Crie hábitos"
    title_bbox = draw.textbbox((0, 0), title, font=title_font)
    title_w = title_bbox[2] - title_bbox[0]
    draw.text(((WIDTH - title_w) // 2, 150), title, fill=COLORS["white"], font=title_font)

    subtitle = "personalizados"
    sub_bbox = draw.textbbox((0, 0), subtitle, font=title_font)
    sub_w = sub_bbox[2] - sub_bbox[0]
    draw.text(((WIDTH - sub_w) // 2, 240), subtitle, fill=COLORS["teal"], font=title_font)

    # Form mockup
    form_y = 450

    # Emoji picker preview
    emojis = ["✨", "💪", "📚", "🏃", "💧", "🧘", "💤", "🥗"]
    emoji_y = form_y
    emoji_x = 100
    for emoji in emojis:
        draw.ellipse([emoji_x - 40, emoji_y - 40, emoji_x + 40, emoji_y + 40],
                     fill=(255, 255, 255, 30))
        emoji_x += 120

    # Name field
    field_y = form_y + 150
    draw_rounded_rect(draw, (80, field_y, WIDTH - 80, field_y + 100), 20, (255, 255, 255, 20))
    draw.text((120, field_y + 30), "Meditar todas as manhãs", fill=COLORS["white"], font=body_font)

    # Color picker
    color_y = field_y + 180
    draw.text((80, color_y), "Cor", fill=COLORS["gray"], font=body_font)

    colors_list = [COLORS["blue"], COLORS["purple"], COLORS["red"],
                   COLORS["orange"], COLORS["green"], COLORS["teal"]]
    color_x = 80
    for i, color in enumerate(colors_list):
        draw.ellipse([color_x, color_y + 60, color_x + 70, color_y + 130], fill=color)
        if i == 1:  # Selected
            draw.ellipse([color_x - 5, color_y + 55, color_x + 75, color_y + 135],
                         outline=COLORS["white"], width=4)
        color_x += 100

    # Days picker
    days_y = color_y + 220
    draw.text((80, days_y), "Dias da semana", fill=COLORS["gray"], font=body_font)

    days = ["D", "S", "T", "Q", "Q", "S", "S"]
    selected = [False, True, True, True, True, True, False]
    day_x = 80
    for day, sel in zip(days, selected):
        fill = COLORS["purple"] if sel else (255, 255, 255, 30)
        draw.ellipse([day_x, days_y + 60, day_x + 70, days_y + 130], fill=fill)
        draw.text((day_x + 22, days_y + 80), day, fill=COLORS["white"], font=body_font)
        day_x += 100

    # Reminder toggle
    reminder_y = days_y + 220
    draw_rounded_rect(draw, (80, reminder_y, WIDTH - 80, reminder_y + 100), 20, (255, 255, 255, 20))
    draw.text((120, reminder_y + 30), "🔔 Lembrete às 07:00", fill=COLORS["white"], font=body_font)

    # Toggle
    toggle_x = WIDTH - 180
    draw_rounded_rect(draw, (toggle_x, reminder_y + 30, toggle_x + 100, reminder_y + 70),
                      20, COLORS["green"])
    draw.ellipse([toggle_x + 55, reminder_y + 32, toggle_x + 95, reminder_y + 68],
                 fill=COLORS["white"])

    # Create button
    btn_y = reminder_y + 200
    draw_rounded_rect(draw, (80, btn_y, WIDTH - 80, btn_y + 100), 25, COLORS["purple"])
    btn_text = "Criar Hábito"
    btn_bbox = draw.textbbox((0, 0), btn_text, font=body_font)
    btn_w = btn_bbox[2] - btn_bbox[0]
    draw.text(((WIDTH - btn_w) // 2, btn_y + 30), btn_text, fill=COLORS["white"], font=body_font)

    return img

def create_screenshot_5():
    """iCloud Sync Screenshot"""
    img = create_gradient_background(WIDTH, HEIGHT)
    draw = ImageDraw.Draw(img)

    try:
        title_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 72)
        body_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 36)
    except:
        title_font = body_font = ImageFont.load_default()

    # Title
    title = "Sincronize"
    title_bbox = draw.textbbox((0, 0), title, font=title_font)
    title_w = title_bbox[2] - title_bbox[0]
    draw.text(((WIDTH - title_w) // 2, 150), title, fill=COLORS["white"], font=title_font)

    subtitle = "com iCloud"
    sub_bbox = draw.textbbox((0, 0), subtitle, font=title_font)
    sub_w = sub_bbox[2] - sub_bbox[0]
    draw.text(((WIDTH - sub_w) // 2, 240), subtitle, fill=COLORS["blue"], font=title_font)

    # Cloud icon (simplified)
    cloud_y = 600
    center_x = WIDTH // 2

    # Draw cloud shape
    draw.ellipse([center_x - 180, cloud_y - 80, center_x + 180, cloud_y + 120],
                 fill=COLORS["white"])
    draw.ellipse([center_x - 250, cloud_y, center_x - 50, cloud_y + 150],
                 fill=COLORS["white"])
    draw.ellipse([center_x + 50, cloud_y - 20, center_x + 250, cloud_y + 130],
                 fill=COLORS["white"])
    draw.rectangle([center_x - 200, cloud_y + 50, center_x + 200, cloud_y + 150],
                   fill=COLORS["white"])

    # Sync arrows
    draw.polygon([(center_x - 40, cloud_y + 50), (center_x, cloud_y), (center_x + 40, cloud_y + 50)],
                 fill=COLORS["blue"])
    draw.rectangle([center_x - 15, cloud_y + 50, center_x + 15, cloud_y + 100], fill=COLORS["blue"])

    # Features
    features = [
        "☁️  Backup automático",
        "📱  Acesse de qualquer dispositivo",
        "🔒  Dados seguros e privados",
        "⚡  Sincronização em tempo real"
    ]

    feat_y = 950
    for feature in features:
        draw_rounded_rect(draw, (100, feat_y, WIDTH - 100, feat_y + 100), 20, (255, 255, 255, 20))
        draw.text((140, feat_y + 30), feature, fill=COLORS["white"], font=body_font)
        feat_y += 130

    # Sign in with Apple button mockup
    btn_y = HEIGHT - 350
    draw_rounded_rect(draw, (100, btn_y, WIDTH - 100, btn_y + 100), 25, COLORS["white"])

    apple_text = " Continuar com Apple"
    apple_bbox = draw.textbbox((0, 0), apple_text, font=body_font)
    apple_w = apple_bbox[2] - apple_bbox[0]
    draw.text(((WIDTH - apple_w) // 2, btn_y + 30), apple_text, fill=(0, 0, 0), font=body_font)

    return img

def main():
    output_dir = "/Users/neog/Apps/iOS/HabitTracker2026-iOS/AppStoreAssets/Screenshots"
    os.makedirs(output_dir, exist_ok=True)

    screenshots = [
        ("01_Welcome", create_screenshot_1),
        ("02_Habits", create_screenshot_2),
        ("03_Streaks", create_screenshot_3),
        ("04_AddHabit", create_screenshot_4),
        ("05_iCloud", create_screenshot_5),
    ]

    print("Creating App Store screenshots...")

    for name, create_func in screenshots:
        print(f"  Creating {name}...")
        img = create_func()

        # Save for each required size
        for size_name, (w, h) in SIZES.items():
            resized = img.resize((w, h), Image.Resampling.LANCZOS)
            filename = f"{name}_{size_name.replace('.', '_')}inch.png"
            resized.save(os.path.join(output_dir, filename), "PNG")

        # Also save original
        img.save(os.path.join(output_dir, f"{name}.png"), "PNG")

    print(f"\nDone! Screenshots saved to: {output_dir}")
    print("\nFiles created:")
    for f in sorted(os.listdir(output_dir)):
        if f.endswith('.png') and not f.startswith('raw'):
            print(f"  - {f}")

if __name__ == "__main__":
    main()
