#!/usr/bin/env python3
"""
Generate humorous, data-driven Valentine's Day cards based on the
U.S. Chocolate Market Report findings.

Each card features:
- Valentine's Day color scheme (pinks, reds, warm tones)
- A data-driven pun or joke from the market report
- Professional but playful design using PIL
"""

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

# ── paths ────────────────────────────────────────────────────────────
SESSION = "/app/sandbox/session_20260212_152520_8a0952fc765d"
OUT_DIR = os.path.join(SESSION, "figures")
os.makedirs(OUT_DIR, exist_ok=True)

# ── fonts ────────────────────────────────────────────────────────────
FONT_SANS       = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
FONT_SANS_BOLD  = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
FONT_SERIF      = "/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf"
FONT_SERIF_BOLD = "/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf"

# ── palette ──────────────────────────────────────────────────────────
DEEP_RED     = (180, 30, 50)
BLUSH_PINK   = (255, 182, 193)
HOT_PINK     = (255, 105, 135)
CREAM        = (255, 248, 240)
DARK_CHOC    = (65, 25, 15)
MILK_CHOC    = (120, 60, 30)
ROSE_GOLD    = (183, 110, 121)
WHITE        = (255, 255, 255)
SOFT_RED     = (220, 60, 80)
WARM_PINK    = (245, 200, 210)
BURGUNDY     = (128, 0, 32)
LIGHT_GOLD   = (255, 223, 186)

CARD_W, CARD_H = 1200, 800  # landscape card

random.seed(42)


# ── helper: draw hearts ─────────────────────────────────────────────
def draw_heart(draw, cx, cy, size, fill, outline=None):
    """Draw a simple heart shape centred at (cx, cy)."""
    pts = []
    for deg in range(360):
        t = math.radians(deg)
        x = 16 * math.sin(t)**3
        y = -(13 * math.cos(t) - 5 * math.cos(2*t) - 2 * math.cos(3*t) - math.cos(4*t))
        pts.append((cx + x * size / 16, cy + y * size / 16))
    draw.polygon(pts, fill=fill, outline=outline)


def draw_mini_hearts(draw, n=12, size_range=(8, 18), color=BLUSH_PINK):
    """Scatter small hearts randomly for decoration."""
    for _ in range(n):
        x = random.randint(30, CARD_W - 30)
        y = random.randint(30, CARD_H - 30)
        s = random.randint(*size_range)
        alpha_color = tuple(list(color) + [180])  # won't work on RGB; just use color
        draw_heart(draw, x, y, s, fill=color)


def draw_chocolate_bar_border(draw, color=MILK_CHOC, seg=12):
    """Draw a segmented chocolate-bar style border."""
    bw = 18  # border width
    seg_w = CARD_W // seg
    seg_h = CARD_H // seg
    for i in range(seg):
        shade = tuple(max(0, c + random.randint(-15, 15)) for c in color)
        # top
        draw.rectangle([i * seg_w, 0, (i+1) * seg_w, bw], fill=shade)
        # bottom
        draw.rectangle([i * seg_w, CARD_H - bw, (i+1) * seg_w, CARD_H], fill=shade)
    for i in range(seg):
        shade = tuple(max(0, c + random.randint(-15, 15)) for c in color)
        # left
        draw.rectangle([0, i * seg_h, bw, (i+1) * seg_h], fill=shade)
        # right
        draw.rectangle([CARD_W - bw, i * seg_h, CARD_W, (i+1) * seg_h], fill=shade)


def text_wrapped(draw, text, font, max_width, x, y, fill, align="center",
                 line_spacing=8):
    """Draw text with word-wrapping."""
    words = text.split()
    lines = []
    current = ""
    for w in words:
        test = f"{current} {w}".strip()
        bbox = draw.textbbox((0, 0), test, font=font)
        if bbox[2] - bbox[0] > max_width and current:
            lines.append(current)
            current = w
        else:
            current = test
    if current:
        lines.append(current)

    total_h = sum(draw.textbbox((0, 0), l, font=font)[3] - draw.textbbox((0, 0), l, font=font)[1]
                  for l in lines) + line_spacing * (len(lines) - 1)
    cur_y = y - total_h // 2
    for line in lines:
        bbox = draw.textbbox((0, 0), line, font=font)
        lw = bbox[2] - bbox[0]
        lh = bbox[3] - bbox[1]
        if align == "center":
            draw.text((x - lw // 2, cur_y), line, font=font, fill=fill)
        elif align == "left":
            draw.text((x, cur_y), line, font=font, fill=fill)
        cur_y += lh + line_spacing
    return cur_y


def draw_rounded_rect(draw, xy, radius, fill, outline=None, width=1):
    """Draw a rounded rectangle."""
    x0, y0, x1, y1 = xy
    r = radius
    draw.rectangle([x0 + r, y0, x1 - r, y1], fill=fill)
    draw.rectangle([x0, y0 + r, x1, y1 - r], fill=fill)
    draw.pieslice([x0, y0, x0 + 2*r, y0 + 2*r], 180, 270, fill=fill)
    draw.pieslice([x1 - 2*r, y0, x1, y0 + 2*r], 270, 360, fill=fill)
    draw.pieslice([x0, y1 - 2*r, x0 + 2*r, y1], 90, 180, fill=fill)
    draw.pieslice([x1 - 2*r, y1 - 2*r, x1, y1], 0, 90, fill=fill)
    if outline:
        draw.arc([x0, y0, x0 + 2*r, y0 + 2*r], 180, 270, fill=outline, width=width)
        draw.arc([x1 - 2*r, y0, x1, y0 + 2*r], 270, 360, fill=outline, width=width)
        draw.arc([x0, y1 - 2*r, x0 + 2*r, y1], 90, 180, fill=outline, width=width)
        draw.arc([x1 - 2*r, y1 - 2*r, x1, y1], 0, 90, fill=outline, width=width)
        draw.line([x0 + r, y0, x1 - r, y0], fill=outline, width=width)
        draw.line([x0 + r, y1, x1 - r, y1], fill=outline, width=width)
        draw.line([x0, y0 + r, x0, y1 - r], fill=outline, width=width)
        draw.line([x1, y0 + r, x1, y1 - r], fill=outline, width=width)


# ═══════════════════════════════════════════════════════════════════
# CARD 1: Cocoa Price Love
# ═══════════════════════════════════════════════════════════════════
def card_cocoa_price():
    print("  Creating Card 1: Cocoa Price Love...")
    img = Image.new("RGB", (CARD_W, CARD_H), CREAM)
    draw = ImageDraw.Draw(img)

    # Chocolate border
    draw_chocolate_bar_border(draw, DARK_CHOC, seg=14)

    # Big heart behind text
    draw_heart(draw, CARD_W // 2, CARD_H // 2 - 20, 180, fill=SOFT_RED)

    # Scatter mini hearts
    random.seed(1)
    draw_mini_hearts(draw, n=18, size_range=(6, 14), color=BLUSH_PINK)

    # Title
    font_title = ImageFont.truetype(FONT_SERIF_BOLD, 52)
    font_body  = ImageFont.truetype(FONT_SANS_BOLD, 34)
    font_stat  = ImageFont.truetype(FONT_SANS, 26)
    font_tag   = ImageFont.truetype(FONT_SANS, 18)

    text_wrapped(draw, "My love for you is like", font_body, 900,
                 CARD_W // 2, CARD_H // 2 - 80, WHITE)

    text_wrapped(draw, "COCOA PRICES", font_title, 900,
                 CARD_W // 2, CARD_H // 2 - 15, WHITE)

    text_wrapped(draw, "at an ALL-TIME HIGH.", font_body, 900,
                 CARD_W // 2, CARD_H // 2 + 50, WHITE)

    # Stat callout box
    draw_rounded_rect(draw, (350, CARD_H - 160, 850, CARD_H - 80), 18,
                      fill=DARK_CHOC, outline=LIGHT_GOLD, width=2)
    text_wrapped(draw, "$12,931 per metric ton — Dec 2024 peak",
                 font_stat, 480, CARD_W // 2, CARD_H - 118, LIGHT_GOLD)

    # Tagline
    draw.text((CARD_W // 2 - 150, CARD_H - 55),
              "177% surge, and still climbing for you",
              font=font_tag, fill=ROSE_GOLD)

    path = os.path.join(OUT_DIR, "valentine_card_1_cocoa_price.png")
    img.save(path, dpi=(300, 300))
    print(f"  -> Saved: {path}")
    return path


# ═══════════════════════════════════════════════════════════════════
# CARD 2: Shrinkflation Promise
# ═══════════════════════════════════════════════════════════════════
def card_shrinkflation():
    print("  Creating Card 2: Shrinkflation Promise...")
    img = Image.new("RGB", (CARD_W, CARD_H), WARM_PINK)
    draw = ImageDraw.Draw(img)

    draw_chocolate_bar_border(draw, MILK_CHOC, seg=14)

    # Decorative hearts
    random.seed(2)
    draw_mini_hearts(draw, n=15, size_range=(6, 16), color=HOT_PINK)

    # Two hearts: big and small (illustrating "shrinkflation")
    draw_heart(draw, 300, CARD_H // 2 - 40, 120, fill=DEEP_RED)
    draw_heart(draw, 500, CARD_H // 2 - 10, 55, fill=DEEP_RED, outline=WHITE)
    # Arrow from big to small
    draw.line([(370, CARD_H // 2 - 40), (460, CARD_H // 2 - 20)],
              fill=DARK_CHOC, width=4)
    draw.polygon([(460, CARD_H // 2 - 30), (475, CARD_H // 2 - 20),
                  (460, CARD_H // 2 - 10)], fill=DARK_CHOC)

    font_title = ImageFont.truetype(FONT_SERIF_BOLD, 44)
    font_body  = ImageFont.truetype(FONT_SANS, 32)
    font_stat  = ImageFont.truetype(FONT_SANS_BOLD, 24)
    font_tag   = ImageFont.truetype(FONT_SANS, 18)

    text_wrapped(draw, "I promise to NEVER", font_body, 500,
                 850, CARD_H // 2 - 80, DARK_CHOC)
    text_wrapped(draw, '"shrinkflation"', font_title, 500,
                 850, CARD_H // 2 - 20, DEEP_RED)
    text_wrapped(draw, "our time together.", font_body, 500,
                 850, CARD_H // 2 + 45, DARK_CHOC)

    # Stat box
    draw_rounded_rect(draw, (250, CARD_H - 150, 950, CARD_H - 70), 16,
                      fill=DARK_CHOC, outline=BLUSH_PINK, width=2)
    text_wrapped(draw,
                 "Boxed chocolates: up 11.8% in price, down in size. Our love? Never.",
                 font_stat, 660, CARD_W // 2, CARD_H - 108, CREAM)

    draw.text((CARD_W // 2 - 120, CARD_H - 50),
              "Same wrapper, less chocolate. Not us.",
              font=font_tag, fill=BURGUNDY)

    path = os.path.join(OUT_DIR, "valentine_card_2_shrinkflation.png")
    img.save(path, dpi=(300, 300))
    print(f"  -> Saved: {path}")
    return path


# ═══════════════════════════════════════════════════════════════════
# CARD 3: Market Share of My Heart
# ═══════════════════════════════════════════════════════════════════
def card_market_share():
    print("  Creating Card 3: Market Share of My Heart...")
    img = Image.new("RGB", (CARD_W, CARD_H), CREAM)
    draw = ImageDraw.Draw(img)

    draw_chocolate_bar_border(draw, DEEP_RED, seg=14)

    random.seed(3)
    draw_mini_hearts(draw, n=10, size_range=(5, 12), color=WARM_PINK)

    # Draw a large heart as "pie chart" — fill entirely
    draw_heart(draw, CARD_W // 2, CARD_H // 2 - 30, 200, fill=SOFT_RED)

    # Overlay "100%" text
    font_pct  = ImageFont.truetype(FONT_SANS_BOLD, 72)
    bbox = draw.textbbox((0, 0), "100%", font=font_pct)
    tw = bbox[2] - bbox[0]
    draw.text((CARD_W // 2 - tw // 2, CARD_H // 2 - 60), "100%",
              font=font_pct, fill=WHITE)

    font_title = ImageFont.truetype(FONT_SERIF_BOLD, 40)
    font_body  = ImageFont.truetype(FONT_SANS, 30)
    font_stat  = ImageFont.truetype(FONT_SANS, 22)
    font_tag   = ImageFont.truetype(FONT_SANS, 17)

    text_wrapped(draw, "You have", font_body, 900,
                 CARD_W // 2, 65, DARK_CHOC)
    text_wrapped(draw, "MARKET SHARE OF MY HEART", font_title, 900,
                 CARD_W // 2, 110, DEEP_RED)

    # Stat callout
    draw_rounded_rect(draw, (200, CARD_H - 155, 1000, CARD_H - 70), 16,
                      fill=DARK_CHOC, outline=ROSE_GOLD, width=2)
    text_wrapped(draw,
                 "Hershey's has 35.5%. Mars has ~30%. You? All of mine.",
                 font_stat, 760, CARD_W // 2, CARD_H - 110, CREAM)

    draw.text((CARD_W // 2 - 190, CARD_H - 50),
              "U.S. chocolate market: $28.91B. You: priceless.",
              font=font_tag, fill=ROSE_GOLD)

    path = os.path.join(OUT_DIR, "valentine_card_3_market_share.png")
    img.save(path, dpi=(300, 300))
    print(f"  -> Saved: {path}")
    return path


# ═══════════════════════════════════════════════════════════════════
# CARD 4: Valentine's Spending Spree
# ═══════════════════════════════════════════════════════════════════
def card_spending():
    print("  Creating Card 4: Valentine's Spending Spree...")
    # Gradient-ish background
    img = Image.new("RGB", (CARD_W, CARD_H), DEEP_RED)
    draw = ImageDraw.Draw(img)
    # Gradient stripes
    for y in range(CARD_H):
        r = int(DEEP_RED[0] + (BURGUNDY[0] - DEEP_RED[0]) * y / CARD_H)
        g = int(DEEP_RED[1] + (BURGUNDY[1] - DEEP_RED[1]) * y / CARD_H)
        b = int(DEEP_RED[2] + (BURGUNDY[2] - DEEP_RED[2]) * y / CARD_H)
        draw.line([(0, y), (CARD_W, y)], fill=(r, g, b))

    draw_chocolate_bar_border(draw, LIGHT_GOLD, seg=16)

    random.seed(4)
    draw_mini_hearts(draw, n=20, size_range=(8, 20), color=HOT_PINK)

    font_title = ImageFont.truetype(FONT_SERIF_BOLD, 52)
    font_body  = ImageFont.truetype(FONT_SANS, 34)
    font_big   = ImageFont.truetype(FONT_SANS_BOLD, 80)
    font_stat  = ImageFont.truetype(FONT_SANS, 22)
    font_tag   = ImageFont.truetype(FONT_SANS, 17)

    text_wrapped(draw, "Americans will spend", font_body, 900,
                 CARD_W // 2, 120, CREAM)

    # Big dollar amount
    bbox = draw.textbbox((0, 0), "$29.1 B", font=font_big)
    tw = bbox[2] - bbox[0]
    draw.text((CARD_W // 2 - tw // 2, 170), "$29.1 B",
              font=font_big, fill=LIGHT_GOLD)

    text_wrapped(draw, "on Valentine's Day.", font_body, 900,
                 CARD_W // 2, 290, CREAM)

    # The punchline
    draw_heart(draw, CARD_W // 2, CARD_H // 2 + 60, 100, fill=HOT_PINK)
    text_wrapped(draw, "I'd spend", font_body, 600,
                 CARD_W // 2, CARD_H // 2 + 20, WHITE)
    text_wrapped(draw, "$29.2B", font_title, 600,
                 CARD_W // 2, CARD_H // 2 + 70, WHITE)
    text_wrapped(draw, "on you.", font_body, 600,
                 CARD_W // 2, CARD_H // 2 + 130, WHITE)

    # Stat bar
    draw_rounded_rect(draw, (200, CARD_H - 130, 1000, CARD_H - 55), 14,
                      fill=(40, 10, 10), outline=LIGHT_GOLD, width=2)
    text_wrapped(draw,
                 "58 million lbs of chocolate bought during V-Day week alone",
                 font_stat, 760, CARD_W // 2, CARD_H - 90, CREAM)

    draw.text((CARD_W // 2 - 120, CARD_H - 40),
              "56% of consumers buy candy. Be mine.",
              font=font_tag, fill=BLUSH_PINK)

    path = os.path.join(OUT_DIR, "valentine_card_4_spending.png")
    img.save(path, dpi=(300, 300))
    print(f"  -> Saved: {path}")
    return path


# ═══════════════════════════════════════════════════════════════════
# CARD 5: Gen Z Unexpected Textures
# ═══════════════════════════════════════════════════════════════════
def card_gen_z():
    print("  Creating Card 5: Gen Z Unexpected Textures...")
    img = Image.new("RGB", (CARD_W, CARD_H), (255, 228, 225))  # misty rose
    draw = ImageDraw.Draw(img)

    draw_chocolate_bar_border(draw, ROSE_GOLD, seg=14)

    random.seed(5)
    draw_mini_hearts(draw, n=14, size_range=(6, 14), color=SOFT_RED)

    # Decorative hearts cluster on left
    for i, (ox, oy, sz) in enumerate([(100, 200, 50), (160, 320, 35),
                                       (80, 440, 45), (190, 150, 25),
                                       (130, 550, 30)]):
        draw_heart(draw, ox, oy, sz, fill=HOT_PINK if i % 2 == 0 else SOFT_RED)

    font_title = ImageFont.truetype(FONT_SERIF_BOLD, 46)
    font_body  = ImageFont.truetype(FONT_SANS, 32)
    font_stat  = ImageFont.truetype(FONT_SANS_BOLD, 24)
    font_tag   = ImageFont.truetype(FONT_SANS, 18)

    cx = CARD_W // 2 + 80  # shift text right to balance hearts

    text_wrapped(draw, "52% of Gen Z crave", font_body, 600,
                 cx, 150, DARK_CHOC)

    text_wrapped(draw, '"UNEXPECTED', font_title, 600,
                 cx, 220, DEEP_RED)
    text_wrapped(draw, 'TEXTURES"', font_title, 600,
                 cx, 280, DEEP_RED)

    text_wrapped(draw, "in chocolate.", font_body, 600,
                 cx, 350, DARK_CHOC)

    # Heart with punchline
    draw_heart(draw, cx, 490, 90, fill=DEEP_RED)
    font_punch = ImageFont.truetype(FONT_SANS_BOLD, 24)
    text_wrapped(draw, "That's why", font_punch, 200,
                 cx, 465, WHITE)
    text_wrapped(draw, "I fell for YOU.", font_punch, 200,
                 cx, 505, WHITE)

    # Stat bar
    draw_rounded_rect(draw, (250, CARD_H - 140, 1000, CARD_H - 60), 16,
                      fill=DARK_CHOC, outline=BLUSH_PINK, width=2)
    text_wrapped(draw,
                 "61% cite environmental impact for plant-based choices, too.",
                 font_stat, 700, 625, CARD_H - 98, CREAM)

    draw.text((CARD_W // 2 - 130, CARD_H - 42),
              "One-of-a-kind, sustainably sourced love.",
              font=font_tag, fill=BURGUNDY)

    path = os.path.join(OUT_DIR, "valentine_card_5_gen_z.png")
    img.save(path, dpi=(300, 300))
    print(f"  -> Saved: {path}")
    return path


# ═══════════════════════════════════════════════════════════════════
# Main
# ═══════════════════════════════════════════════════════════════════
if __name__ == "__main__":
    print("=" * 60)
    print("  Valentine's Day Cards — Chocolate Market Edition")
    print("=" * 60)

    cards = [
        card_cocoa_price,
        card_shrinkflation,
        card_market_share,
        card_spending,
        card_gen_z,
    ]

    paths = []
    for i, fn in enumerate(cards, 1):
        print(f"\n[{i}/{len(cards)}] Generating card...")
        p = fn()
        paths.append(p)

    print("\n" + "=" * 60)
    print("  ALL DONE — 5 Valentine's cards generated!")
    print("=" * 60)
    for p in paths:
        print(f"  {p}")
    print()
