#!/usr/bin/env python3
"""Generate EN favicon: black rounded-square bg, red arrow mark."""
from PIL import Image, ImageDraw
import struct, io, math, os

RED   = (220, 38, 38)   # #DC2626
BLACK = (0, 0, 0)

def draw_en_mark(draw, size, bg_radius_ratio=0.22):
    """Draw the EN arrow mark scaled to `size` pixels."""
    s = size

    # Coordinate mapping from SVG viewBox "0 0 100 100"
    def pt(x, y):
        return (x / 100 * s, y / 100 * s)

    # ── Background: rounded black square ──
    r = int(s * bg_radius_ratio)
    draw.rounded_rectangle([0, 0, s - 1, s - 1], radius=r, fill=BLACK)

    # ── Right wing: solid red triangle ──
    right = [pt(50, 18), pt(74, 82), pt(50, 64)]
    draw.polygon(right, fill=RED)

    # ── Left wing: red open-path stroke ──
    # Simulate open path M50 18 L26 82 L50 64 (no close)
    # Draw as thick polyline
    stroke_w = max(2, int(s * 0.035))
    left_pts = [pt(50, 18), pt(26, 82), pt(50, 64)]
    draw.line(left_pts, fill=RED, width=stroke_w, joint="curve")

def make_icon(size):
    img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
    draw = ImageDraw.Draw(img)
    draw_en_mark(draw, size)
    return img

# ── Sizes to generate ──
sizes = [16, 32, 48, 64, 128, 192, 256, 512]
icons = {s: make_icon(s) for s in sizes}

OUT = os.path.join(os.path.dirname(__file__), "favicon_out")
os.makedirs(OUT, exist_ok=True)

# Save PNGs
for s, img in icons.items():
    img.save(os.path.join(OUT, f"icon_{s}.png"))

# Save apple-touch-icon (180x180 — no transparency, solid bg)
ati = make_icon(180)
ati.save(os.path.join(OUT, "apple-touch-icon.png"))

# Save icon.png (192)
icons[192].save(os.path.join(OUT, "icon.png"))

# Build favicon.ico (multi-resolution: 16, 32, 48, 256)
ico_sizes = [16, 32, 48, 256]
ico_images = []
for s in ico_sizes:
    buf = io.BytesIO()
    img = icons[s].convert("RGBA")
    img.save(buf, format="PNG")
    ico_images.append((s, buf.getvalue()))

# ICO format: header + directory + image data
num = len(ico_images)
header = struct.pack("<HHH", 0, 1, num)  # reserved, type=1 (ICO), count

offsets = []
offset = 6 + num * 16  # header size + directory entries
for s, data in ico_images:
    offsets.append(offset)
    offset += len(data)

directory = b""
for i, (s, data) in enumerate(ico_images):
    w = 0 if s == 256 else s   # ICO spec: 0 means 256
    h = 0 if s == 256 else s
    directory += struct.pack("<BBBBHHII",
        w, h,           # width, height
        0,              # color count (0 = no palette)
        0,              # reserved
        1,              # color planes
        32,             # bits per pixel
        len(data),      # size of image data
        offsets[i]      # offset to image data
    )

ico_bytes = header + directory + b"".join(d for _, d in ico_images)

with open(os.path.join(OUT, "favicon.ico"), "wb") as f:
    f.write(ico_bytes)

print(f"Generated in {OUT}:")
for fn in sorted(os.listdir(OUT)):
    size = os.path.getsize(os.path.join(OUT, fn))
    print(f"  {fn}  ({size} bytes)")
