"""Builds web-ready images (public/images) from the design source files.

Florals arrive on a white background; color-to-alpha against white makes them
blend into any light page tint. Run: python scripts/prepare-images.py
"""
import os
import numpy as np
from PIL import Image

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC = os.path.join(ROOT, "design")
OUT = os.path.join(ROOT, "web", "public", "images")
os.makedirs(OUT, exist_ok=True)


def white_to_alpha(im):
    a = np.asarray(im.convert("RGB")).astype(np.float32) / 255.0
    alpha = np.clip((1.0 - a).max(axis=2), 0, 1)
    safe = np.where(alpha > 1e-4, alpha, 1.0)[..., None]
    rgb = np.clip((a - (1.0 - alpha[..., None])) / safe, 0, 1)
    out = np.dstack([rgb, alpha]) * 255
    return Image.fromarray(out.astype(np.uint8))


def clean_wash(im, floor=0.1, gold_only=False):
    """Drop the faint watercolor wash around a cropped element (it shows as a box)."""
    a = np.asarray(im).astype(np.float32)
    alpha = a[..., 3] / 255.0
    alpha = np.clip((alpha - floor) / (1 - floor), 0, 1)
    if gold_only:
        r, b = a[..., 0], a[..., 2]
        alpha *= np.clip((r - b - 10) / 40.0, 0, 1)
    a[..., 3] = alpha * 255
    return Image.fromarray(a.astype(np.uint8))


def fade_edges(im, sides="", frac=0.12):
    """Soften crop edges ("r", "b", "l", "t") so cut leaves don't end in a hard line."""
    a = np.asarray(im).astype(np.float32)
    h, w = a.shape[:2]
    for side in sides:
        if side in "lr":
            n = int(w * frac)
            fade = np.linspace(0, 1, n)[None, :]
            sl = (slice(None), slice(w - n, w)) if side == "r" else (slice(None), slice(0, n))
            a[sl + (3,)] *= fade[:, ::-1] if side == "r" else fade
        else:
            n = int(h * frac)
            fade = np.linspace(0, 1, n)[:, None]
            sl = (slice(h - n, h), slice(None)) if side == "b" else (slice(0, n), slice(None))
            a[sl + (3,)] *= fade[::-1, :] if side == "b" else fade
    return Image.fromarray(a.astype(np.uint8))


def save(im, name, width=None, quality=82):
    if width and im.width > width:
        im = im.resize((width, round(im.height * width / im.width)), Image.LANCZOS)
    im.save(os.path.join(OUT, name), "WEBP", quality=quality, method=4)
    print(name, im.size)


def attached(name):
    return Image.open(os.path.join(SRC, "attached", name))


def docx(name):
    return Image.open(os.path.join(SRC, "from-docx", name)).convert("RGB")


# Decorative florals
save(white_to_alpha(attached("7.jpg")), "floral-garland.webp", 1800)
bouquet = fade_edges(clean_wash(white_to_alpha(attached("2.png").crop((0, 0, 990, 960))), 0.06), "rb")
save(bouquet, "floral-corner.webp", 800)
leaves = white_to_alpha(attached("9.png"))
save(fade_edges(clean_wash(leaves.crop((960, 0, 1414, 950))), "lb"), "leaves-top.webp", 454)
save(fade_edges(clean_wash(leaves.crop((0, 1040, 430, 2000))), "rt"), "leaves-bottom.webp", 430)
save(clean_wash(leaves.crop((1110, 1690, 1414, 2000)), 0.05, gold_only=True), "gold-swirl.webp", 304)

# Logos
logo = attached("4.png").convert("RGBA")
logo.save(os.path.join(OUT, "logo.png"), optimize=True)
save(logo, "logo.webp", quality=92)
save(white_to_alpha(docx("9_image3.jpg")), "logo-moment.webp", quality=92)
icon = logo.crop((260, 0, 432, 220))  # the infinity mark only
side = max(icon.size)
square = Image.new("RGBA", (side, side), (0, 0, 0, 0))
square.paste(icon, ((side - icon.width) // 2, (side - icon.height) // 2))
square.resize((180, 180), Image.LANCZOS).save(os.path.join(OUT, "apple-touch-icon.png"))
square.resize((64, 64), Image.LANCZOS).save(os.path.join(OUT, "favicon.png"))

# Photos and illustrations (name -> source)
photos = {
    "shani-flowers": "2_image1.jpeg",
    "shani-smile": "3_image5.jpeg",
    "shani-vivian": "8_image1.jpeg",
    "bridge-sketch": "3_image1.jpeg",
    "bridge-color": "3_image4.jpeg",
    "faces-wall": "3_image3.jpeg",
    "hand-how": "3_image2.jpeg",
    "white-canvas": "4_image1.jpeg",
    "herbs-woman": "4_image2.jpeg",
    "library": "4_image3.jpeg",
    "alchemy": "5_image1.jpeg",
    "four-bodies": "5_image2.jpeg",
    "aroma-meditation": "5_image3.jpeg",
    "collage": "5_image4.jpeg",
    "recipes-board": "6_image1.jpeg",
    "spices": "6_image2.jpeg",
    "meditation-hands": "7_image1.jpeg",
    "light-bokeh": "1_image1.jpeg",
}
for name, src in photos.items():
    save(docx(src), f"{name}.webp", 1200, quality=80)

# Restored from the old site (see scripts/import_old.py → extract_images)
OLD_SRC = os.path.join(SRC, "old-site")
if os.path.isdir(OLD_SRC):
    for f in sorted(os.listdir(OLD_SRC)):
        name, _ = os.path.splitext(f)
        im = Image.open(os.path.join(OLD_SRC, f))
        if name.startswith("old-recipe-"):
            # illustrations on white: flatten onto white so cards stay clean
            bg = Image.new("RGB", im.size, "white")
            bg.paste(im.convert("RGBA"), mask=im.convert("RGBA").split()[3])
            save(bg, f"{name}.webp", 800, quality=85)
        else:
            save(im.convert("RGB"), f"{name}.webp", 1400, quality=80)
        if name == "old-values-list":
            w, h = im.size
            save(im.convert("RGB").crop((0, 0, w, int(w * 0.52))), "old-values-cover.webp", 1000, quality=82)
