"""Golden fixtures for the shared text layout algorithm (``spec/fixtures/text-layout.fixtures.json``).

Regenerate (after an intentional, reviewed algorithm change)::

    python -m snapfile_render.tools.text_fixtures --update

The same file is consumed by the TypeScript implementation (``textLayout.ts``) — the frontend MUST
produce identical line breaks, texts and widths (±0.01 pt) for every case.
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any

from ..fontmetrics import FontMetrics
from ..fontprep import prepare_font
from ..providers import BUNDLED_FONTS_DIR
from ..text.layout import layout_text

SPEC_DIR = Path(__file__).resolve().parents[3] / "spec"
FIXTURES = SPEC_DIR / "fixtures" / "text-layout.fixtures.json"
METRICS_DIR = SPEC_DIR / "fixtures" / "metrics"

FONT_FILES = {
    "inter-400": "inter/Inter-Regular.ttf",
    "inter-400-italic": "inter/Inter-Italic.ttf",
    "inter-500": "inter/Inter-Medium.ttf",
    "inter-600": "inter/Inter-SemiBold.ttf",
    "inter-700": "inter/Inter-Bold.ttf",
}

LOREM_EN = (
    "The quick brown fox jumps over the lazy dog while the market outlook remains positive "
    "for long-term investors who value diversification."
)
LOREM_RU = (
    "Уважаемый Иван Иванович, мы подготовили для вас персональное инвестиционное предложение "
    "с учётом вашего профиля риска и долгосрочных целей."
)


def R(text: str, font: str = "inter-400", size: float = 10, **kw: Any) -> dict[str, Any]:
    run = {"text": text, "font": font, "size": size, "letterSpacing": 0, "lineHeight": 1.2}
    run.update(kw)
    return run


def P(*runs: dict[str, Any], **kw: Any) -> dict[str, Any]:
    para: dict[str, Any] = {"align": "left", "indent": 0, "spaceBefore": 0, "spaceAfter": 0, "runs": list(runs)}
    para.update(kw)
    return para


def B(w: float, h: float = 0, **kw: Any) -> dict[str, Any]:
    box: dict[str, Any] = {
        "w": w,
        "h": h,
        "autoSize": "height",
        "overflowMode": "clip",
        "maxLines": None,
        "minFontSize": None,
        "verticalAlign": "top",
        "paragraphSpacing": 0,
    }
    box.update(kw)
    return box


def cases() -> list[dict[str, Any]]:
    c: list[tuple[str, str, list[dict[str, Any]], dict[str, Any], bool]] = [
        ("single-word", "One short word fits on one line", [P(R("Snapfile"))], B(200), True),
        ("two-words-wrap", "Second word does not fit and wraps", [P(R("Portfolio allocation"))], B(60), True),
        ("paragraph-left", "Greedy first-fit wrapping of an English paragraph", [P(R(LOREM_EN))], B(180), True),
        ("paragraph-center", "Center alignment", [P(R(LOREM_EN), align="center")], B(180), True),
        ("paragraph-right", "Right alignment", [P(R(LOREM_EN), align="right")], B(180), True),
        (
            "paragraph-justify",
            "Justify: extra space split between inner spaces; last line left",
            [P(R(LOREM_EN), align="justify")],
            B(180),
            True,
        ),
        (
            "justify-hardbreak",
            "Line before a hard break is not justified",
            [P(R("Short line here\nand the next line is a little bit longer than the box width"), align="justify")],
            B(150),
            True,
        ),
        ("hard-break", "\\n inside a run forces a line break", [P(R("First line\nSecond line"))], B(300), True),
        ("double-hard-break", "Two \\n produce an empty line", [P(R("Above\n\nBelow"))], B(300), True),
        ("trailing-hard-break", "Trailing \\n produces a final empty line", [P(R("Text\n"))], B(300), True),
        ("leading-spaces", "Spaces at the start of a line are dropped", [P(R("   indented by spaces"))], B(300), True),
        ("multiple-spaces", "Every U+0020 is a separate space token", [P(R("a    b"))], B(300), True),
        ("hanging-spaces", "Trailing spaces do not count in line width", [P(R("alpha beta    gamma"))], B(60), True),
        ("hyphen-break", "Break opportunity after '-'", [P(R("A well-known long-established firm"))], B(70), True),
        ("en-dash-break", "Break opportunity after en dash", [P(R("2024–2025–2026–2027–2028 range"))], B(60), True),
        ("em-dash-break", "Break opportunity after em dash", [P(R("Risk—return—balance—discipline"))], B(70), True),
        ("slash-break", "Break opportunity after '/'", [P(R("and/or either/neither stocks/bonds"))], B(55), True),
        (
            "soft-hyphen-eol",
            "Soft hyphen at line end is drawn as '-'",
            [P(R("Diversi­fication strat­egies"))],
            B(45),
            True,
        ),
        ("soft-hyphen-inline", "Soft hyphen inside a line is invisible", [P(R("Diversi­fication"))], B(300), True),
        (
            "zero-width-space",
            "U+200B is an invisible break opportunity",
            [P(R("verylong​compound​identifier"))],
            B(60),
            True,
        ),
        ("nbsp", "U+00A0 does not break", [P(R("100 000 USD and 25 % share"))], B(55), True),
        ("narrow-nbsp", "U+202F does not break", [P(R("1 500 000 roubles"))], B(40), True),
        (
            "emergency-break",
            "A word wider than the box breaks by characters",
            [P(R("Supercalifragilisticexpialidocious"))],
            B(60),
            True,
        ),
        (
            "emergency-min-char",
            "At least one character per line even if it does not fit",
            [P(R("WWW", size=20))],
            B(5),
            True,
        ),
        (
            "mixed-runs-word",
            "Run boundary inside a word is not a break opportunity",
            [P(R("Invest"), R("ment", font="inter-700"), R(" plan for 2027"))],
            B(60),
            True,
        ),
        (
            "mixed-sizes",
            "Line height = max; baseline from the largest size",
            [P(R("Small "), R("BIG", size=24), R(" small again and more words to wrap"))],
            B(150),
            True,
        ),
        ("line-height-pt", "lineHeight as explicit points", [P(R(LOREM_EN, lineHeight={"pt": 18}))], B(200), True),
        (
            "letter-spacing",
            "Positive letterSpacing adds after each char",
            [P(R("SPACED TITLE", letterSpacing=2))],
            B(300),
            True,
        ),
        (
            "letter-spacing-negative",
            "Negative letterSpacing",
            [P(R("Tight heading text", letterSpacing=-0.5, size=18))],
            B(300),
            True,
        ),
        ("kerning-on", "Kerning pairs AV, To, Ty, LT applied", [P(R("AVATAR To Tyre LT WAVE", size=20))], B(400), True),
        ("kerning-off", "Same text with kerning disabled", [P(R("AVATAR To Tyre LT WAVE", size=20))], B(400), False),
        ("cyrillic-wrap", "Cyrillic paragraph", [P(R(LOREM_RU))], B(200), True),
        ("cyrillic-kerning", "Cyrillic kerning pairs", [P(R("ТОТ Ть Г, У. Тут", size=20))], B(400), True),
        ("case-upper", "textCase upper incl. ß -> SS", [P(R("straße report", textCase="upper"))], B(300), True),
        ("case-lower", "textCase lower", [P(R("QUARTERLY Report", textCase="lower"))], B(300), True),
        (
            "case-title",
            "textCase title: shared rule",
            [P(R("risk-taking ENVIRONMENT (core) и «рынок»", textCase="title"))],
            B(400),
            True,
        ),
        ("nfc", "Decomposed é is normalised to NFC", [P(R("Café résumé"))], B(300), True),
        ("tab", "Tab becomes a space", [P(R("Name:\tValue"))], B(300), True),
        ("crlf", "CRLF is a single hard break", [P(R("Line one\r\nLine two"))], B(300), True),
        (
            "paragraphs-spacing-before-after",
            "spaceBefore / spaceAfter",
            [P(R("First paragraph"), spaceAfter=6), P(R("Second paragraph"), spaceBefore=4)],
            B(300),
            True,
        ),
        (
            "paragraph-spacing",
            "paragraphSpacing between paragraphs",
            [P(R("One")), P(R("Two")), P(R("Three"))],
            B(300, paragraphSpacing=10),
            True,
        ),
        ("indent", "First-line indent reduces first line width", [P(R(LOREM_EN), indent=20)], B(180), True),
        ("indent-center", "Indent with center alignment", [P(R(LOREM_EN), indent=20, align="center")], B(180), True),
        (
            "autosize-width",
            "autoSize width: no wrapping, width = longest line",
            [P(R("Auto width label"))],
            B(10, 14, autoSize="width"),
            True,
        ),
        (
            "autosize-width-multiline",
            "autoSize width with \\n and center alignment",
            [P(R("Short\nA much longer second line"), align="center")],
            B(10, 14, autoSize="width"),
            True,
        ),
        ("autosize-height", "autoSize height: height = text height", [P(R(LOREM_RU))], B(160, 10), True),
        (
            "fixed-clip",
            "Fixed box: lines whose baseline+descent exceed h are dropped",
            [P(R(LOREM_EN))],
            B(180, 30, autoSize="none"),
            True,
        ),
        (
            "fixed-clip-none-fit",
            "Fixed box too small for the first line",
            [P(R("Hello world", size=20))],
            B(180, 10, autoSize="none"),
            True,
        ),
        (
            "ellipsis",
            "Ellipsis on the last visible line",
            [P(R(LOREM_EN))],
            B(180, 30, autoSize="none", overflowMode="ellipsis"),
            True,
        ),
        (
            "ellipsis-maxlines",
            "maxLines=1 with ellipsis",
            [P(R(LOREM_EN))],
            B(180, 100, autoSize="none", overflowMode="ellipsis", maxLines=1),
            True,
        ),
        (
            "ellipsis-autoheight-maxlines",
            "autoSize height + maxLines 2 + ellipsis flag",
            [P(R(LOREM_RU))],
            B(160, 0, maxLines=2, ellipsis=True),
            True,
        ),
        (
            "ellipsis-multirun",
            "Ellipsis takes the style of the last kept character",
            [P(R("Client: "), R("Иванов Иван Иванович Petrovsky-Longname", font="inter-700"))],
            B(120, 14, autoSize="none", overflowMode="ellipsis"),
            True,
        ),
        (
            "ellipsis-right",
            "Ellipsis with right alignment",
            [P(R(LOREM_EN), align="right")],
            B(150, 14, autoSize="none", overflowMode="ellipsis"),
            True,
        ),
        (
            "shrink-fit",
            "Shrink: binary search of the font scale",
            [P(R(LOREM_EN, size=14))],
            B(180, 60, autoSize="none", overflowMode="shrink", minFontSize=6),
            True,
        ),
        (
            "shrink-not-needed",
            "Shrink keeps scale 1 when text fits",
            [P(R("Fits", size=14))],
            B(180, 60, autoSize="none", overflowMode="shrink", minFontSize=6),
            True,
        ),
        (
            "shrink-min-ellipsis",
            "Shrink reaches minFontSize then ellipsis + TEXT_OVERFLOW",
            [P(R(LOREM_EN * 3, size=14))],
            B(120, 30, autoSize="none", overflowMode="shrink", minFontSize=8),
            True,
        ),
        (
            "shrink-maxlines",
            "Shrink honours maxLines",
            [P(R("Investment Proposal Summary", size=24))],
            B(200, 100, autoSize="none", overflowMode="shrink", minFontSize=8, maxLines=1),
            True,
        ),
        (
            "valign-middle",
            "verticalAlign middle in fixed box",
            [P(R("Centered"))],
            B(100, 40, autoSize="none", verticalAlign="middle"),
            True,
        ),
        (
            "valign-bottom",
            "verticalAlign bottom in fixed box",
            [P(R("Bottom"))],
            B(100, 40, autoSize="none", verticalAlign="bottom"),
            True,
        ),
        ("empty-run", "Empty text keeps one empty line", [P(R(""))], B(100), True),
        ("empty-paragraph-list", "Paragraph without runs uses the fallback style", [P()], B(100), True),
        (
            "italic",
            "Italic face metrics",
            [P(R("Italic emphasis in a sentence", font="inter-400-italic"))],
            B(120),
            True,
        ),
        (
            "weights",
            "Medium/SemiBold/Bold runs in one line",
            [P(R("Medium ", font="inter-500"), R("SemiBold ", font="inter-600"), R("Bold", font="inter-700"))],
            B(300),
            True,
        ),
        (
            "digits-punctuation",
            "Digits and punctuation",
            [P(R("1 234 567,89 ₽ — 12.5% (YoY), $1,500.50; 3/4"))],
            B(120),
            True,
        ),
        ("long-text-justify-ru", "Justified Cyrillic text", [P(R(LOREM_RU * 2), align="justify")], B(220), True),
        ("small-size", "Very small size", [P(R(LOREM_EN, size=5))], B(100), True),
    ]
    out = []
    for cid, desc, paras, box, kerning in c:
        out.append({"id": cid, "description": desc, "input": {"paragraphs": paras, "box": box, "kerning": kerning}})
    return out


def _metrics() -> dict[str, FontMetrics]:
    out: dict[str, FontMetrics] = {}
    for key in FONT_FILES:
        path = METRICS_DIR / f"{key}.json"
        if path.exists():
            out[key] = FontMetrics.from_file(key, path)
    return out


def write_metrics() -> None:
    METRICS_DIR.mkdir(parents=True, exist_ok=True)
    for key, rel in FONT_FILES.items():
        prepared = prepare_font((BUNDLED_FONTS_DIR / rel).read_bytes())
        (METRICS_DIR / f"{key}.json").write_text(json.dumps(prepared.metrics, separators=(",", ":")), encoding="utf-8")


def compute(case: dict[str, Any], metrics: dict[str, FontMetrics]) -> dict[str, Any]:
    inp = case["input"]
    return layout_text(
        inp["paragraphs"],
        inp["box"],
        lambda k: metrics[k],
        kerning=inp["kerning"],
        fallback_run={"font": "inter-400", "size": 10, "lineHeight": 1.2},
    )


def build() -> dict[str, Any]:
    metrics = _metrics()
    items = []
    for case in cases():
        case["expected"] = compute(case, metrics)
        items.append(case)
    return {
        "version": 1,
        "algorithm": "spec/text-layout.md",
        "tolerance": {"position_pt": 0.01, "breaks": "exact", "text": "exact"},
        "fonts": {k: f"metrics/{k}.json" for k in FONT_FILES},
        "fallbackRun": {"font": "inter-400", "size": 10, "lineHeight": 1.2},
        "cases": items,
    }


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--update", action="store_true", help="rewrite metrics and fixtures")
    args = ap.parse_args(argv)
    if args.update:
        write_metrics()
        data = build()
        FIXTURES.write_text(json.dumps(data, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
        print(f"wrote {len(data['cases'])} cases to {FIXTURES}")
        return 0
    data = json.loads(FIXTURES.read_text(encoding="utf-8"))
    metrics = _metrics()
    failed = [c["id"] for c in data["cases"] if compute(c, metrics) != c["expected"]]
    print("OK" if not failed else f"MISMATCH: {failed}")
    return 1 if failed else 0


if __name__ == "__main__":
    sys.exit(main())
