#!/usr/bin/env python3
"""Task 16 — Generate FIGHTSKILL PWA icons from the brand favicon design.

Brand: dark #131019 rounded square + neon-green F monogram with a dot,
gradient #8C64EB -> #5F6FD3 (same geometry as app/static/favicon.svg).

Outputs (app/static/icons/):
  icon-192.png / icon-512.png          rounded, transparent corners (install UI)
  maskable-192.png / maskable-512.png  full-bleed, F shrunk into 80% safe zone
  apple-touch-icon.png                 180x180 full-bleed (iOS crops corners itself)
  favicon-32.png / favicon-16.png      small rounded fallbacks
"""
import os
import numpy as np
from PIL import Image, ImageDraw

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUT = os.path.join(ROOT, "app", "static", "icons")
os.makedirs(OUT, exist_ok=True)

BG = (19, 16, 25)        # #131019
GREEN_1 = (140, 100, 235)  # #8C64EB
GREEN_2 = (95, 111, 211)  # 0x5F6FD3

# F monogram in a 64x64 viewbox (verbatim from favicon.svg)
F_POLY = [(20, 15), (45, 15), (45, 22.5), (28.5, 22.5), (28.5, 28.5),
          (42.5, 28.5), (42.5, 36), (28.5, 36), (28.5, 49), (20, 49)]
DOT = (32.5, 10.5, 2.2)  # cx, cy, r


def scale(pts, s):
    return [(x * s, y * s) for x, y in pts]


def gradient_layer(size):
    """Diagonal (#8C64EB top-left -> #5F6FD3 bottom-right) RGB layer."""
    xx, yy = np.meshgrid(np.arange(size, dtype=np.float32),
                         np.arange(size, dtype=np.float32))
    t = (xx + yy) / (2.0 * max(size - 1, 1))
    arr = np.zeros((size, size, 3), dtype=np.uint8)
    for i in range(3):
        arr[..., i] = (GREEN_1[i] + (GREEN_2[i] - GREEN_1[i]) * t).astype(np.uint8)
    return Image.fromarray(arr, "RGB")


def draw_brand(size, pad_ratio=0.0, content_scale=1.0, ring=True):
    """Render the brand mark onto a full-bleed BG square of `size`.

    content_scale < 1 shrinks the F+dot towards center (maskable safe zone).
    """
    canvas = Image.new("RGBA", (size, size), BG + (255,))
    s = size / 64.0 * content_scale
    off = (size - 64.0 * s) / 2.0  # centering offset for scaled content

    poly = [(x * s + off, y * s + off) for x, y in F_POLY]
    cx, cy, r = DOT[0] * s + off, DOT[1] * s + off, DOT[2] * s

    # mask with F + dot
    mask = Image.new("L", (size, size), 0)
    md = ImageDraw.Draw(mask)
    md.polygon(poly, fill=255)
    md.ellipse([cx - r, cy - r, cx + r, cy + r], fill=255)

    grad = gradient_layer(size).convert("RGBA")
    canvas.paste(grad, (0, 0), mask)

    if ring:
        d = ImageDraw.Draw(canvas)
        inset = max(1, round(size * 1.5 / 64))
        d.rounded_rectangle([inset, inset, size - inset, size - inset],
                            radius=round(12.5 * size / 64),
                            outline=GREEN_1 + (90,), width=max(1, round(2 * size / 64)))
    return canvas


def rounded_mask(size, radius):
    m = Image.new("L", (size, size), 0)
    ImageDraw.Draw(m).rounded_rectangle([0, 0, size - 1, size - 1],
                                        radius=radius, fill=255)
    return m


def save(img, name):
    path = os.path.join(OUT, name)
    img.save(path, "PNG", optimize=True)
    print(f"  ✓ {name}  {img.size[0]}x{img.size[1]}")


print("Generating FIGHTSKILL PWA icons →", OUT)

# 1) Standard icons: rounded square, transparent outside (like favicon.svg)
for size, name in [(512, "icon-512.png"), (192, "icon-192.png")]:
    img = draw_brand(size)
    img.putalpha(rounded_mask(size, round(size * 14 / 64)))
    save(img, name)

# 2) Maskable: full-bleed, content inside the central 80% safe zone
for size, name in [(512, "maskable-512.png"), (192, "maskable-192.png")]:
    save(draw_brand(size, content_scale=0.72, ring=False), name)

# 3) Apple touch icon: full-bleed 180x180 (iOS applies its own corner mask)
save(draw_brand(180, content_scale=0.92), "apple-touch-icon.png")

# 4) Small favicons (rounded, transparent)
for size, name in [(32, "favicon-32.png"), (16, "favicon-16.png")]:
    img = draw_brand(size)
    img.putalpha(rounded_mask(size, round(size * 14 / 64)))
    save(img, name)

print("Done.")
