"""Deterministische omslagen uit de titel: statische SVG, zonder verhaaltekst."""

from __future__ import annotations

import hashlib
import math
import re
from pathlib import Path

# 2:3, een gangbaar coverformaat in leesapps.
WIDTH = 240
HEIGHT = 360
MARGIN_X = 18
MARGIN_Y = 22
TEXT_AREA_BOTTOM = 24
BAND_PADDING = 16


def title_key(title: str) -> str:
    return (title or "").strip() or "Untitled"


def title_hash(title: str) -> str:
    return hashlib.sha256(title_key(title).encode("utf-8")).hexdigest()


def cover_relpath(title: str) -> str:
    digest = title_hash(title)
    return f"covers/{digest[:2]}/{digest[:20]}.svg"


def _hsl_to_hex(h: float, s: float, l: float) -> str:
    """h in [0, 360), s en l in [0, 1]."""
    h = h % 360
    c = (1 - abs(2 * l - 1)) * s
    x = c * (1 - abs((h / 60) % 2 - 1))
    m = l - c / 2
    if h < 60:
        r, g, b = c, x, 0
    elif h < 120:
        r, g, b = x, c, 0
    elif h < 180:
        r, g, b = 0, c, x
    elif h < 240:
        r, g, b = 0, x, c
    elif h < 300:
        r, g, b = x, 0, c
    else:
        r, g, b = c, 0, x
    return "#{:02x}{:02x}{:02x}".format(round((r + m) * 255), round((g + m) * 255), round((b + m) * 255))


def palette(title: str) -> dict:
    digest = title_hash(title)
    nums = [int(digest[i : i + 2], 16) for i in range(0, 16, 2)]
    h1 = nums[0] / 255 * 360
    h2 = (h1 + 28 + nums[1] / 255 * 80) % 360
    s1 = 0.48 + nums[2] / 255 * 0.32
    s2 = 0.42 + nums[3] / 255 * 0.32
    l1 = 0.30 + nums[4] / 255 * 0.18
    l2 = 0.22 + nums[5] / 255 * 0.16
    variant = nums[6] % 6
    angle = nums[7] / 255 * 360
    return {
        "c1": _hsl_to_hex(h1, s1, l1),
        "c2": _hsl_to_hex(h2, s2, l2),
        "c3": _hsl_to_hex((h1 + 180) % 360, 0.35, 0.55),
        "variant": variant,
        "angle": angle,
        "digest": digest,
    }


def _char_width(font_size: int) -> float:
    # Ruime schatting voor een vet sans-serif, zodat regels niet over de rand lopen.
    return font_size * 0.62


def max_chars_for(font_size: int) -> int:
    usable = WIDTH - 2 * MARGIN_X
    return max(8, int(usable / _char_width(font_size)))


def wrap_title(title: str, max_chars: int, max_lines: int) -> list[str]:
    """Breek de titel op woorden, en midden in een te lang woord."""
    text = re.sub(r"\s+", " ", title_key(title)).strip()
    if not text:
        return ["Untitled"]

    def break_word(word: str) -> list[str]:
        if len(word) <= max_chars:
            return [word]
        parts = []
        rest = word
        while len(rest) > max_chars:
            # Laat ruimte voor een koppelteken, behalve als we later ellipsis zetten.
            cut = max_chars - 1
            parts.append(rest[:cut] + "-")
            rest = rest[cut:]
        if rest:
            parts.append(rest)
        return parts

    words: list[str] = []
    for raw in text.split(" "):
        words.extend(break_word(raw))

    lines: list[str] = []
    current = ""
    for word in words:
        trial = word if not current else current + " " + word
        if len(trial) <= max_chars:
            current = trial
            continue
        if current:
            lines.append(current)
        current = word
    if current:
        lines.append(current)

    if len(lines) > max_lines:
        lines = lines[:max_lines]
        last = lines[-1]
        budget = max(1, max_chars - 1)
        if len(last) > budget:
            last = last[:budget].rstrip(" -")
        lines[-1] = last.rstrip(" -") + "…"
    return lines


def choose_layout(title: str) -> tuple[int, list[str]]:
    """Kies een lettergrootte zodat de titel past; zo nodig ellipsis."""
    for font_size, max_lines in ((26, 5), (22, 6), (18, 7), (16, 8)):
        lines = wrap_title(title, max_chars_for(font_size), max_lines=99)
        if len(lines) <= max_lines and not (lines and lines[-1].endswith("…")):
            return font_size, lines
    font_size, max_lines = 16, 8
    return font_size, wrap_title(title, max_chars_for(font_size), max_lines)


def _esc(text: str) -> str:
    return (
        text.replace("&", "&amp;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace('"', "&quot;")
    )


def _background(pal: dict, gid: str) -> str:
    c1, c2, c3 = pal["c1"], pal["c2"], pal["c3"]
    variant = pal["variant"]
    angle = pal["angle"]
    rad = math.radians(angle)
    x2 = 0.5 + math.cos(rad) / 2
    y2 = 0.5 + math.sin(rad) / 2
    defs = [
        f'<linearGradient id="{gid}" x1="0" y1="0" x2="{x2:.3f}" y2="{y2:.3f}">',
        f'<stop offset="0%" stop-color="{c1}"/>',
        f'<stop offset="100%" stop-color="{c2}"/>',
        "</linearGradient>",
    ]
    body = [f'<rect width="{WIDTH}" height="{HEIGHT}" fill="url(#{gid})"/>']
    if variant == 1:
        body.append(
            f'<circle cx="{WIDTH * 0.78:.0f}" cy="{HEIGHT * 0.22:.0f}" r="90" fill="{c3}" fill-opacity="0.28"/>'
        )
        body.append(
            f'<circle cx="{WIDTH * 0.12:.0f}" cy="{HEIGHT * 0.7:.0f}" r="70" fill="{c1}" fill-opacity="0.25"/>'
        )
    elif variant == 2:
        pid = gid + "p"
        defs.append(
            f'<pattern id="{pid}" width="28" height="28" patternUnits="userSpaceOnUse"'
            f' patternTransform="rotate({angle:.0f})">'
            f'<rect width="14" height="28" fill="{c3}" fill-opacity="0.22"/>'
            "</pattern>"
        )
        body.append(f'<rect width="{WIDTH}" height="{HEIGHT}" fill="url(#{pid})"/>')
    elif variant == 3:
        body.append(
            f'<circle cx="{WIDTH * 0.3:.0f}" cy="{HEIGHT * 0.32:.0f}" r="110" fill="{c3}" fill-opacity="0.22"/>'
        )
        body.append(
            f'<circle cx="{WIDTH * 0.85:.0f}" cy="{HEIGHT * 0.55:.0f}" r="95" fill="{c2}" fill-opacity="0.28"/>'
        )
    elif variant == 4:
        body.append(
            f'<rect x="40" y="40" width="160" height="160" rx="8" transform="rotate(32 120 120)" '
            f'fill="{c3}" fill-opacity="0.18"/>'
        )
        body.append(
            f'<rect x="20" y="160" width="130" height="130" rx="8" transform="rotate(-18 85 225)" '
            f'fill="{c1}" fill-opacity="0.22"/>'
        )
    elif variant == 5:
        for i, y in enumerate(range(0, HEIGHT, 36)):
            if i % 2 == 0:
                body.append(f'<rect x="0" y="{y}" width="{WIDTH}" height="18" fill="{c3}" fill-opacity="0.16"/>')
    return "<defs>" + "".join(defs) + "</defs>" + "".join(body)


def render_svg(title: str) -> str:
    pal = palette(title)
    font_size, lines = choose_layout(title)
    line_height = round(font_size * 1.22)
    text_block = line_height * len(lines)
    band_top = HEIGHT - TEXT_AREA_BOTTOM - text_block - BAND_PADDING * 2
    band_top = max(HEIGHT * 0.42, band_top)
    band_height = HEIGHT - band_top
    gid = "g" + pal["digest"][:10]
    # Tekst onderaan, gecentreerd, op de donkere band.
    first_baseline = band_top + BAND_PADDING + font_size
    tspans = []
    for i, line in enumerate(lines):
        y = first_baseline + i * line_height
        tspans.append(
            f'<tspan x="{WIDTH // 2}" y="{y}">{_esc(line)}</tspan>'
        )
    svg = (
        f'<svg xmlns="http://www.w3.org/2000/svg" width="{WIDTH}" height="{HEIGHT}" '
        f'viewBox="0 0 {WIDTH} {HEIGHT}" role="img" aria-label="{_esc(title_key(title))}">'
        f"{_background(pal, gid)}"
        f'<rect x="0" y="{band_top:.1f}" width="{WIDTH}" height="{band_height:.1f}" fill="#0b1020" fill-opacity="0.55"/>'
        f'<text font-family="Trebuchet MS, Segoe UI, sans-serif" font-size="{font_size}" '
        f'font-weight="700" fill="#f7f4ef" text-anchor="middle" '
        f'stroke="#0b1020" stroke-width="0.8" paint-order="stroke">'
        + "".join(tspans)
        + "</text></svg>\n"
    )
    return svg


def prune_unused_covers(dest_root: Path, keep: set[str]) -> None:
    root = Path(dest_root) / "covers"
    if not root.exists():
        return
    keep_stems = {Path(name).stem for name in keep}
    for path in list(root.rglob("*.svg")) + list(root.rglob("*.png")):
        if path.stem not in keep_stems:
            path.unlink()
    for folder in sorted(root.rglob("*"), reverse=True):
        if folder.is_dir() and not any(folder.iterdir()):
            folder.rmdir()


# Alleen voor de tests: hoe hoog staat de laatste regel, past alles in het vlak?
def text_bounds(title: str) -> dict:
    font_size, lines = choose_layout(title)
    line_height = round(font_size * 1.22)
    text_block = line_height * len(lines)
    band_top = max(HEIGHT * 0.42, HEIGHT - TEXT_AREA_BOTTOM - text_block - BAND_PADDING * 2)
    first_baseline = band_top + BAND_PADDING + font_size
    last_baseline = first_baseline + (len(lines) - 1) * line_height
    # Ruime descent (~0.25 em) onder de baseline.
    last_bottom = last_baseline + font_size * 0.3
    return {
        "font_size": font_size,
        "lines": lines,
        "line_max_chars": max_chars_for(font_size),
        "band_top": band_top,
        "last_bottom": last_bottom,
        "width": WIDTH,
        "height": HEIGHT,
    }


FONT_PATH = Path(__file__).resolve().parent / "fonts" / "DejaVuSans-Bold.ttf"


def _font(size: int):
    from PIL import ImageFont

    if FONT_PATH.is_file():
        return ImageFont.truetype(str(FONT_PATH), size=size)
    return ImageFont.load_default()


def _lerp(a: tuple[int, int, int], b: tuple[int, int, int], t: float) -> tuple[int, int, int]:
    return tuple(int(a[i] + (b[i] - a[i]) * t) for i in range(3))  # type: ignore[return-value]


def _hex_rgb(color: str) -> tuple[int, int, int]:
    h = color.lstrip("#")
    return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)


def _angled_gradient(c1: tuple[int, int, int], c2: tuple[int, int, int], angle: float) -> "Image.Image":
    from PIL import Image, ImageDraw

    diag = int(math.hypot(WIDTH, HEIGHT)) + 4
    band = Image.new("RGB", (diag, diag))
    draw = ImageDraw.Draw(band)
    last = diag - 1 or 1
    for y in range(diag):
        draw.line((0, y, diag, y), fill=_lerp(c1, c2, y / last))
    band = band.rotate(-angle, resample=Image.Resampling.BILINEAR, expand=False)
    cx, cy = band.size[0] // 2, band.size[1] // 2
    return band.crop((cx - WIDTH // 2, cy - HEIGHT // 2, cx - WIDTH // 2 + WIDTH, cy - HEIGHT // 2 + HEIGHT))


def render_png(title: str) -> bytes:
    """Zelfde indeling als de SVG, als PNG-bytes (voor LNReader / expo-image)."""
    from io import BytesIO

    from PIL import Image, ImageDraw

    pal = palette(title)
    font_size, lines = choose_layout(title)
    c1, c2, c3 = _hex_rgb(pal["c1"]), _hex_rgb(pal["c2"]), _hex_rgb(pal["c3"])
    img = _angled_gradient(c1, c2, pal["angle"]).convert("RGBA")
    overlay = Image.new("RGBA", (WIDTH, HEIGHT), (0, 0, 0, 0))
    od = ImageDraw.Draw(overlay)
    variant = pal["variant"]
    if variant == 1:
        od.ellipse((WIDTH * 0.78 - 90, HEIGHT * 0.22 - 90, WIDTH * 0.78 + 90, HEIGHT * 0.22 + 90), fill=(*c3, 71))
        od.ellipse((WIDTH * 0.12 - 70, HEIGHT * 0.7 - 70, WIDTH * 0.12 + 70, HEIGHT * 0.7 + 70), fill=(*c1, 64))
    elif variant == 2:
        step = 28
        for i in range(-HEIGHT, WIDTH + HEIGHT, step):
            od.polygon(
                [(i, 0), (i + 14, 0), (i + 14 - HEIGHT, HEIGHT), (i - HEIGHT, HEIGHT)],
                fill=(*c3, 56),
            )
    elif variant == 3:
        od.ellipse((WIDTH * 0.3 - 110, HEIGHT * 0.32 - 110, WIDTH * 0.3 + 110, HEIGHT * 0.32 + 110), fill=(*c3, 56))
        od.ellipse((WIDTH * 0.85 - 95, HEIGHT * 0.55 - 95, WIDTH * 0.85 + 95, HEIGHT * 0.55 + 95), fill=(*c2, 71))
    elif variant == 4:
        od.regular_polygon((120, 120, 90), 4, rotation=32, fill=(*c3, 46))
        od.regular_polygon((85, 225, 70), 4, rotation=-18, fill=(*c1, 56))
    elif variant == 5:
        for i, y in enumerate(range(0, HEIGHT, 36)):
            if i % 2 == 0:
                od.rectangle((0, y, WIDTH, y + 18), fill=(*c3, 41))
    img = Image.alpha_composite(img, overlay)

    line_height = round(font_size * 1.22)
    text_block = line_height * len(lines)
    band_top = max(HEIGHT * 0.42, HEIGHT - TEXT_AREA_BOTTOM - text_block - BAND_PADDING * 2)
    draw = ImageDraw.Draw(img)
    draw.rectangle((0, int(band_top), WIDTH, HEIGHT), fill=(11, 16, 32, 140))
    font = _font(font_size)
    first_baseline = band_top + BAND_PADDING + font_size
    for i, line in enumerate(lines):
        y = first_baseline + i * line_height
        draw.text((WIDTH / 2 + 1, y + 1), line, font=font, fill=(11, 16, 32, 220), anchor="ms")
        draw.text((WIDTH / 2, y), line, font=font, fill=(247, 244, 239, 255), anchor="ms")

    buf = BytesIO()
    quantized = img.convert("RGB").quantize(colors=64, method=Image.Quantize.MEDIANCUT)
    quantized.save(buf, format="PNG", optimize=True, compress_level=9)
    return buf.getvalue()


def write_cover(dest_root: Path, title: str) -> str:
    """Schrijf een coverbestand. PNG als Pillow beschikbaar is (voor LNReader), anders SVG."""
    dest_root = Path(dest_root)
    svg_rel = cover_relpath(title)
    try:
        png_bytes = render_png(title)
        rel = svg_rel[:-4] + ".png"
        path = dest_root / rel
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(png_bytes)
        return path.relative_to(dest_root).as_posix()
    except Exception:
        path = dest_root / svg_rel
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(render_svg(title), encoding="utf-8")
        return path.relative_to(dest_root).as_posix()
