#!/usr/bin/env python3
"""Build square PNG and WebP exports for every approved logo SVG."""

from __future__ import annotations

import json
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import xml.etree.ElementTree as ET

from PIL import Image, ImageColor


ROOT = Path(__file__).resolve().parents[1]
LOGO_DIR = ROOT / "logos"
RASTER_DIR = LOGO_DIR / "raster"
FAVICON_DIR = LOGO_DIR / "favicon"
LIBRARY_VERSION = 2
SIZES = (16, 32, 48, 64, 128, 256, 512, 1024)
FAVICON_SIZES = (16, 32, 48)

PRODUCTS = (
    ("packet-warriors", "Packet Warriors"),
    ("firefly", "Firefly"),
    ("xlx-observatory", "XLX Observatory"),
    ("fwdfix", "FwdFix"),
    ("gps-clock-dash", "GPS Clock Dash"),
)

VARIANTS = {
    "flat-dark": "Flat / dark",
    "flat-light": "Flat / light",
    "mono-dark": "Monochrome / dark",
    "mono-light": "Monochrome / light",
    "metallic": "Metallic / optional",
    "icon": "Favicon / app tile",
}


def asset_metadata(source: Path) -> dict[str, object]:
    for slug, product in PRODUCTS:
        prefix = f"{slug}-"
        if source.stem.startswith(prefix):
            variant = source.stem.removeprefix(prefix)
            if variant not in VARIANTS:
                break
            return {
                "slug": source.stem,
                "product": product,
                "productSlug": slug,
                "variant": variant,
                "variantLabel": VARIANTS[variant],
                "svg": f"logos/{source.name}",
                "preview": "light" if variant.endswith("light") else "dark",
            }
    raise ValueError(f"Unrecognized approved logo filename: {source.name}")


def render_svg(magick: str, source: Path, target: Path, size: int) -> None:
    target.parent.mkdir(parents=True, exist_ok=True)
    command = [
        magick,
        "-background",
        "none",
        "-density",
        "384",
        str(source),
        "-resize",
        f"{size}x{size}",
        "-gravity",
        "center",
        "-extent",
        f"{size}x{size}",
        "-strip",
        f"PNG32:{target}",
    ]
    subprocess.run(command, check=True)


def gradient_color(stops: list[tuple[float, tuple[int, int, int]]], position: float) -> tuple[int, int, int]:
    for index, (offset, color) in enumerate(stops[1:], start=1):
        if position <= offset:
            previous_offset, previous_color = stops[index - 1]
            span = offset - previous_offset
            amount = 0 if span == 0 else (position - previous_offset) / span
            return tuple(round(start + ((end - start) * amount)) for start, end in zip(previous_color, color))
    return stops[-1][1]


def render_metallic(magick: str, source: Path, target: Path, size: int, fmt: str) -> None:
    """Render the metallic gradients that ImageMagick's SVG delegate drops."""
    namespace = "{http://www.w3.org/2000/svg}"
    root = ET.parse(source).getroot()
    gradients = {
        gradient.attrib["id"]: [
            (
                float(stop.attrib.get("offset", "0").removesuffix("%"))
                / (100 if stop.attrib.get("offset", "0").endswith("%") else 1),
                ImageColor.getrgb(stop.attrib["stop-color"]),
            )
            for stop in gradient.findall(f"{namespace}stop")
        ]
        for gradient in root.findall(f".//{namespace}linearGradient")
    }
    canvas = Image.new("RGBA", (size, size), (0, 0, 0, 0))

    with tempfile.TemporaryDirectory(prefix="pw-logo-") as temporary_directory:
        temporary = Path(temporary_directory)
        for index, path in enumerate(root.findall(f"{namespace}path")):
            match = re.fullmatch(r"url\(#([^)]+)\)", path.attrib.get("fill", ""))
            if match is None or match.group(1) not in gradients:
                raise ValueError(f"Metallic path has no recognized gradient: {source.name}")

            mask_svg = temporary / f"mask-{index}.svg"
            mask_png = temporary / f"mask-{index}.png"
            mask_svg.write_text(
                '<svg xmlns="http://www.w3.org/2000/svg" viewBox="'
                + root.attrib["viewBox"]
                + '"><path fill="#fff" d="'
                + path.attrib["d"]
                + '"/></svg>',
                encoding="utf-8",
            )
            render_svg(magick, mask_svg, mask_png, size)

            mask = Image.open(mask_png).convert("RGBA").getchannel("A")
            solid_bounds = mask.point(lambda value: 255 if value >= 128 else 0).getbbox()
            if solid_bounds is None:
                raise ValueError(f"Metallic path rendered empty: {source.name}")
            top, bottom = solid_bounds[1], solid_bounds[3]
            height = max(bottom - top - 1, 1)
            rows = []
            for y in range(size):
                position = min(1.0, max(0.0, (y - top) / height))
                rows.append(gradient_color(gradients[match.group(1)], position))
            gradient = Image.new("RGB", (1, size))
            gradient.putdata(rows)
            layer = gradient.resize((size, size)).convert("RGBA")
            layer.putalpha(mask)
            canvas.alpha_composite(layer)

    target.parent.mkdir(parents=True, exist_ok=True)
    if fmt == "png":
        canvas.save(target, format="PNG")
    else:
        with tempfile.TemporaryDirectory(prefix="pw-logo-") as temporary_directory:
            png = Path(temporary_directory) / "metallic.png"
            canvas.save(png, format="PNG")
            subprocess.run(
                [magick, str(png), "-define", "webp:lossless=true", str(target)],
                check=True,
            )


def render(magick: str, source: Path, target: Path, size: int, fmt: str) -> None:
    target.parent.mkdir(parents=True, exist_ok=True)
    if source.stem == "packet-warriors-metallic":
        render_metallic(magick, source, target, size, fmt)
        return
    if fmt == "png":
        render_svg(magick, source, target, size)
        return
    subprocess.run(
        [
            magick,
            "-background",
            "none",
            "-density",
            "384",
            str(source),
            "-resize",
            f"{size}x{size}",
            "-gravity",
            "center",
            "-extent",
            f"{size}x{size}",
            "-strip",
            "-define",
            "webp:lossless=true",
            str(target),
        ],
        check=True,
    )


def build_favicon_package(magick: str) -> None:
    source = FAVICON_DIR / "packet-warriors-favicon.svg"
    pngs = []
    for size in FAVICON_SIZES:
        target = FAVICON_DIR / f"favicon-{size}x{size}.png"
        render_svg(magick, source, target, size)
        pngs.append(target)

    render_svg(
        magick,
        source,
        FAVICON_DIR / "apple-touch-icon-180x180.png",
        180,
    )
    subprocess.run(
        [magick, *(str(png) for png in pngs), "-strip", str(FAVICON_DIR / "favicon.ico")],
        check=True,
    )


def main() -> None:
    magick = shutil.which("magick")
    if magick is None:
        raise SystemExit("ImageMagick 7 (`magick`) is required to build logo exports.")

    source_assets = [(source, asset_metadata(source)) for source in LOGO_DIR.glob("*.svg")]
    product_order = {slug: index for index, (slug, _) in enumerate(PRODUCTS)}
    variant_order = {variant: index for index, variant in enumerate(VARIANTS)}
    source_assets.sort(
        key=lambda item: (
            product_order[str(item[1]["productSlug"])],
            variant_order[str(item[1]["variant"])],
        )
    )
    sources = [source for source, _ in source_assets]
    assets = [asset for _, asset in source_assets]

    # These two format trees contain generated files only. Recreate them so
    # removed or renamed source assets cannot leave stale downloads behind.
    for fmt in ("png", "webp"):
        output_dir = RASTER_DIR / fmt
        if output_dir.exists():
            shutil.rmtree(output_dir)

    for source, asset in zip(sources, assets, strict=True):
        raster: dict[str, dict[str, str]] = {}
        for size in SIZES:
            raster[str(size)] = {}
            for fmt in ("png", "webp"):
                filename = f"{source.stem}-{size}x{size}.{fmt}"
                relative = Path("logos") / "raster" / fmt / str(size) / filename
                render(magick, source, ROOT / relative, size, fmt)
                raster[str(size)][fmt] = relative.as_posix()
        asset["raster"] = raster

    build_favicon_package(magick)

    payload = {
        "version": LIBRARY_VERSION,
        "canvas": "square-transparent",
        "sizes": list(SIZES),
        "assets": assets,
    }
    manifest = json.dumps(payload, indent=2) + "\n"
    RASTER_DIR.mkdir(parents=True, exist_ok=True)
    (RASTER_DIR / "manifest.json").write_text(manifest, encoding="utf-8")
    (LOGO_DIR / "logo-library.js").write_text(
        "window.PW_LOGO_LIBRARY = " + json.dumps(payload, separators=(",", ":")) + ";\n",
        encoding="utf-8",
    )
    print(f"Built {len(assets)} logos in {len(SIZES)} sizes as PNG and WebP.")


if __name__ == "__main__":
    main()
