"""Deterministic text layout (TZ 2.6.5). Normative description: ``spec/text-layout.md``.

The TypeScript editor implements exactly the same steps; ``spec/fixtures/text-layout.fixtures.json``
pins the results. Any change here must be mirrored in the spec and fixtures.

Public entry point: :func:`layout_text`. Input/Output are plain dicts (the fixture format).
"""

from __future__ import annotations

import math
import unicodedata
from collections.abc import Callable
from typing import Any

from ..fmt import title_case
from ..fontmetrics import FontMetrics

EPS = 0.01
BREAK_AFTER = frozenset("-–—/­​")
ZERO_WIDTH = frozenset("­​")
SHY = "­"
HYPHEN = "-"
ELLIPSIS = "…"
DEFAULT_MIN_FONT_SIZE = 4.0
SHRINK_MAX_ITER = 8
SHRINK_PRECISION_PT = 0.25

MetricsProvider = Callable[[str], FontMetrics]


def r3(x: float) -> float:
    """Round to 1/1000 pt: floor(x*1000 + 0.5)/1000 (same formula in JS; not banker's rounding)."""
    return math.floor(x * 1000 + 0.5) / 1000


# --------------------------------------------------------------------------------------------- styles


class _Style:
    __slots__ = ("asc", "desc", "idx", "kerning", "lh_mult", "lh_pt", "ls", "m", "size", "upm")

    def __init__(self, idx: int, run: dict[str, Any], metrics: FontMetrics, scale: float, kerning: bool) -> None:
        self.idx = idx
        self.m = metrics
        self.size = float(run.get("size", 12)) * scale
        self.ls = float(run.get("letterSpacing", 0) or 0)
        lh = run.get("lineHeight", 1.2)
        if isinstance(lh, dict):
            self.lh_pt: float | None = float(lh.get("pt", 0)) * scale
            self.lh_mult = 0.0
        else:
            self.lh_pt = None
            self.lh_mult = float(lh if lh is not None else 1.2)
        self.upm = metrics.upm
        self.asc = metrics.ascender
        self.desc = metrics.descender
        self.kerning = kerning

    def line_height(self) -> float:
        return self.lh_pt if self.lh_pt is not None else self.lh_mult * self.size

    def char_width(self, cp: int) -> float:
        return (self.m.advance(cp) * self.size) / self.upm + self.ls


def measure_chars(chars: list[str], style: _Style) -> float:
    """Unrounded width of a same-style char sequence: kerning between neighbours, then advance+ls."""
    w = 0.0
    prev = -1
    size = style.size
    upm = style.upm
    m = style.m
    for ch in chars:
        if ch in ZERO_WIDTH:
            continue
        cp = ord(ch)
        if prev >= 0 and style.kerning:
            k = m.kern(prev, cp)
            if k:
                w += (k * size) / upm
        w += (m.advance(cp) * size) / upm + style.ls
        prev = cp
    return w


# --------------------------------------------------------------------------------------------- tokens

_WORD, _SPACE, _HARD = 0, 1, 2


class _Token:
    __slots__ = ("chars", "kind", "pieces", "style", "width")

    def __init__(self, kind: int, style: _Style, chars: list[tuple[str, _Style]] | None = None) -> None:
        self.kind = kind
        self.style = style
        self.chars = chars or []
        self.pieces: list[tuple[_Style, list[str]]] = []
        self.width = 0.0

    def build(self) -> _Token:
        pieces: list[tuple[_Style, list[str]]] = []
        for ch, st in self.chars:
            if pieces and pieces[-1][0] is st:
                pieces[-1][1].append(ch)
            else:
                pieces.append((st, [ch]))
        self.pieces = pieces
        self.width = r3(sum(measure_chars(chs, st) for st, chs in pieces))
        return self

    def ends_with_shy(self) -> bool:
        return bool(self.chars) and self.chars[-1][0] == SHY


def _space_token(st: _Style) -> _Token:
    tok = _Token(_SPACE, st, [(" ", st)])
    tok.pieces = [(st, [" "])]
    tok.width = r3(st.char_width(32))
    return tok


def _normalize(text: str, text_case: str | None) -> str:
    text = unicodedata.normalize("NFC", text)
    text = text.replace("\r\n", "\n").replace("\r", "\n").replace("\t", " ")
    if text_case == "upper":
        text = text.upper()
    elif text_case == "lower":
        text = text.lower()
    elif text_case == "title":
        text = title_case(text)
    return text


def _tokenize(styled_text: list[tuple[str, _Style]]) -> list[_Token]:
    tokens: list[_Token] = []
    word: list[tuple[str, _Style]] = []

    def flush() -> None:
        if word:
            tokens.append(_Token(_WORD, word[0][1], list(word)).build())
            word.clear()

    for text, st in styled_text:
        for ch in text:
            if ch == "\n":
                flush()
                tokens.append(_Token(_HARD, st))
            elif ch == " ":
                flush()
                tokens.append(_space_token(st))
            else:
                word.append((ch, st))
                if ch in BREAK_AFTER:
                    flush()
    flush()
    return tokens


# --------------------------------------------------------------------------------------------- lines


class _Line:
    __slots__ = ("first", "hard", "items", "last_style", "shy_style", "width", "after_hard")

    def __init__(self, first: bool, style: _Style) -> None:
        self.first = first
        self.items: list[_Token] = []
        self.width = 0.0
        self.hard = False
        self.last_style = style
        self.shy_style: _Style | None = None
        self.after_hard = False


def _break_paragraph(tokens: list[_Token], width: float, indent: float, base_style: _Style) -> list[_Line]:
    lines: list[_Line] = []
    line = _Line(True, base_style)
    pending: list[_Token] = []

    def capacity(ln: _Line) -> float:
        return width - (indent if ln.first else 0.0)

    def close(hard: bool) -> _Line:
        nonlocal line
        pending.clear()
        line.hard = hard
        if not hard and line.items and line.items[-1].ends_with_shy():
            st = line.items[-1].chars[-1][1]
            line.shy_style = st
            line.width = line.width + r3(st.char_width(ord(HYPHEN)))
        lines.append(line)
        nxt = _Line(False, line.last_style)
        nxt.after_hard = hard
        line = nxt
        return nxt

    def add(tok: _Token) -> None:
        for sp in pending:
            line.items.append(sp)
            line.width += sp.width
        pending.clear()
        line.items.append(tok)
        line.width += tok.width
        line.last_style = tok.chars[-1][1] if tok.chars else tok.style

    def emergency(tok: _Token) -> None:
        chars = tok.chars
        while chars:
            cap = capacity(line)
            take = 1
            for n in range(len(chars), 0, -1):
                t = _Token(_WORD, chars[0][1], chars[:n]).build()
                if t.width <= cap + EPS:
                    take = n
                    break
            part = _Token(_WORD, chars[0][1], chars[:take]).build()
            add(part)
            chars = chars[take:]
            if not chars:
                return
            close(False)
            rest = _Token(_WORD, chars[0][1], chars).build()
            if rest.width <= capacity(line) + EPS:
                add(rest)
                return

    for tok in tokens:
        if tok.kind == _HARD:
            line.last_style = tok.style if not line.items else line.last_style
            close(True)
            line.last_style = tok.style
            continue
        if tok.kind == _SPACE:
            if line.items:
                pending.append(tok)
            elif line.first or line.after_hard:
                add(tok)  # typed indent: only a soft wrap drops leading spaces
            continue
        pend = sum(sp.width for sp in pending)
        if not line.items:
            if tok.width <= capacity(line) + EPS:
                add(tok)
            else:
                emergency(tok)
        elif line.width + pend + tok.width <= capacity(line) + EPS:
            add(tok)
        else:
            close(False)
            if tok.width <= capacity(line) + EPS:
                add(tok)
            else:
                emergency(tok)
    close(True)
    lines[-1].hard = False
    return lines


def _line_metrics(line: _Line) -> tuple[float, float, _Style]:
    """Line height and baseline offset from line top (TZ 2.6.5 step 5)."""
    styles: list[_Style] = []
    for tok in line.items:
        for st, _ in tok.pieces:
            styles.append(st)
    if not styles:
        styles = [line.last_style]
    lh = max(st.line_height() for st in styles)
    big = styles[0]
    for st in styles:
        if st.size > big.size:
            big = st
    content = ((big.asc - big.desc) * big.size) / big.upm
    baseline = (lh - content) / 2 + (big.asc * big.size) / big.upm
    return lh, baseline, big


def _glyph_runs(line: _Line, x0: float, word_extra: float) -> list[dict[str, Any]]:
    """Merge the line's tokens into glyph runs (consecutive chars of one source run)."""
    runs: list[dict[str, Any]] = []
    cursor = x0
    for tok in line.items:
        offset = 0.0
        for st, chs in tok.pieces:
            text = "".join(c for c in chs if c not in ZERO_WIDTH)
            if text:
                if runs and runs[-1]["run"] == st.idx:
                    runs[-1]["text"] += text
                else:
                    runs.append({"run": st.idx, "text": text, "x": r3(cursor + r3(offset))})
            offset += measure_chars(chs, st)
        cursor += tok.width
        if tok.kind == _SPACE:
            cursor += word_extra
    if line.shy_style is not None:
        st = line.shy_style
        if runs and runs[-1]["run"] == st.idx:
            runs[-1]["text"] += HYPHEN
        else:
            runs.append({"run": st.idx, "text": HYPHEN, "x": r3(cursor)})
    return runs


def _styles_for(
    runs: list[dict[str, Any]], metrics: MetricsProvider, scale: float, kerning: bool, offset: int
) -> list[_Style]:
    return [_Style(offset + i, r, metrics(r["font"]), scale, kerning) for i, r in enumerate(runs)]


def _layout_paragraphs(
    paragraphs: list[dict[str, Any]],
    width: float,
    metrics: MetricsProvider,
    scale: float,
    kerning: bool,
    paragraph_spacing: float,
    fallback_run: dict[str, Any] | None,
) -> list[dict[str, Any]]:
    out: list[dict[str, Any]] = []
    y = 0.0
    run_offset = 0
    for pi, para in enumerate(paragraphs):
        runs = para.get("runs") or []
        styles = _styles_for(runs, metrics, scale, kerning, run_offset)
        run_offset += len(runs)
        if not styles:
            fb = fallback_run or {"font": "default", "size": 12}
            styles = [_Style(-1, fb, metrics(fb["font"]), scale, kerning)]
            styled: list[tuple[str, _Style]] = []
        else:
            styled = [
                (_normalize(str(r.get("text", "")), r.get("textCase")), st) for r, st in zip(runs, styles, strict=False)
            ]
        indent = float(para.get("indent", 0) or 0)
        align = para.get("align", "left")
        tokens = _tokenize(styled)
        lines = _break_paragraph(tokens, width, indent, styles[0])
        if pi > 0:
            y += paragraph_spacing
        y += float(para.get("spaceBefore", 0) or 0)
        for li, line in enumerate(lines):
            lh, base_off, big = _line_metrics(line)
            avail = width - (indent if line.first else 0.0)
            x0 = indent if line.first else 0.0
            lw = r3(line.width)
            extra = 0.0
            last_of_para = li == len(lines) - 1
            if align == "center":
                x = x0 + (avail - lw) / 2
            elif align == "right":
                x = x0 + avail - lw
            else:
                x = x0
                if align == "justify" and not last_of_para and not line.hard and math.isfinite(avail):
                    n_spaces = sum(1 for t in line.items if t.kind == _SPACE)
                    if n_spaces and lw < avail:
                        extra = (avail - lw) / n_spaces
            if not math.isfinite(x):
                x = x0
            glyph_runs = _glyph_runs(line, x, extra)
            out.append(
                {
                    "paragraph": pi,
                    "top": r3(y),
                    "baseline": r3(y + base_off),
                    "height": r3(lh),
                    "x": r3(x),
                    "width": lw,
                    "wordSpacing": r3(extra),
                    "descent": r3((-big.desc * big.size) / big.upm),
                    "text": "".join(g["text"] for g in glyph_runs),
                    "runs": glyph_runs,
                    "_line": line,
                }
            )
            y += lh
        y += float(para.get("spaceAfter", 0) or 0)
    if out:
        out[-1]["_end"] = r3(y)
    else:
        out.append({"_end": r3(y)})
    return out


def _ellipsize(entry: dict[str, Any], width: float, kerning: bool) -> dict[str, Any]:
    """Cut the line from the end char by char until width(prefix) + width('…') <= available width."""
    line: _Line = entry["_line"]
    chars: list[tuple[str, _Style]] = []
    for tok in line.items:
        chars.extend(tok.chars)
    while chars and chars[-1][0] == " ":
        chars.pop()
    last_style = chars[-1][1] if chars else line.last_style
    avail = width - entry.get("_indent", 0.0)
    n = len(chars)
    while True:
        prefix = chars[:n]
        while prefix and prefix[-1][0] == " ":
            prefix = prefix[:-1]
        st = prefix[-1][1] if prefix else last_style
        ell_w = r3(st.char_width(ord(ELLIPSIS)))
        toks = _tokenize_chars(prefix)
        pw = sum(t.width for t in toks)
        if pw + ell_w <= avail + EPS or not prefix:
            break
        n = len(prefix) - 1
    new_line = _Line(line.first, st)
    for t in toks:
        new_line.items.append(t)
    ell = _Token(_WORD, st, [(ELLIPSIS, st)]).build()
    new_line.items.append(ell)
    new_line.width = pw + ell.width
    entry = dict(entry)
    entry["width"] = r3(new_line.width)
    entry["wordSpacing"] = 0.0
    entry["_line"] = new_line
    entry["truncatedLine"] = True
    return entry


def _tokenize_chars(chars: list[tuple[str, _Style]]) -> list[_Token]:
    tokens: list[_Token] = []
    word: list[tuple[str, _Style]] = []
    for ch, st in chars:
        if ch == " ":
            if word:
                tokens.append(_Token(_WORD, word[0][1], list(word)).build())
                word = []
            tokens.append(_space_token(st))
        else:
            word.append((ch, st))
    if word:
        tokens.append(_Token(_WORD, word[0][1], list(word)).build())
    return tokens


def _realign(entry: dict[str, Any], width: float, align: str, indent: float) -> None:
    line: _Line = entry["_line"]
    x0 = indent if line.first else 0.0
    avail = width - x0
    lw = entry["width"]
    if align == "center":
        x = x0 + (avail - lw) / 2
    elif align == "right":
        x = x0 + avail - lw
    else:
        x = x0
    entry["x"] = r3(x)
    runs = _glyph_runs(line, x, 0.0)
    entry["runs"] = runs
    entry["text"] = "".join(g["text"] for g in runs)


def _fits(lines: list[dict[str, Any]], height: float, max_lines: int | None) -> bool:
    real = [ln for ln in lines if "_line" in ln]
    if max_lines is not None and len(real) > max_lines:
        return False
    return lines[-1]["_end"] <= height + EPS


def layout_text(
    paragraphs: list[dict[str, Any]],
    box: dict[str, Any],
    metrics: MetricsProvider,
    *,
    kerning: bool = True,
    fallback_run: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Lay out text in a box.

    box: ``{"w", "h", "autoSize": none|height|width, "overflowMode": clip|ellipsis|shrink,
    "maxLines", "minFontSize", "verticalAlign": top|middle|bottom, "paragraphSpacing"}``.
    Returns ``{"width", "height", "scale", "truncated", "lines": [...]}`` (see spec/text-layout.md).
    """
    auto = box.get("autoSize", "none") or "none"
    mode = box.get("overflowMode", "clip") or "clip"
    max_lines = box.get("maxLines")
    max_lines = int(max_lines) if max_lines else None
    para_spacing = float(box.get("paragraphSpacing", 0) or 0)
    w = math.inf if auto == "width" else float(box.get("w", 0))
    h = float(box.get("h", 0) or 0)
    scale = 1.0
    warnings: list[str] = []

    def run(k: float) -> list[dict[str, Any]]:
        return _layout_paragraphs(paragraphs, w, metrics, k, kerning, para_spacing, fallback_run)

    lines = run(scale)
    if auto == "none" and mode == "shrink" and not _fits(lines, h, max_lines):
        sizes = [float(r.get("size", 12)) for p in paragraphs for r in (p.get("runs") or [])] or [12.0]
        base = max(sizes)
        min_fs = float(box.get("minFontSize") or DEFAULT_MIN_FONT_SIZE)
        lo, hi = min(1.0, min_fs / base), 1.0
        lo_lines = run(lo)
        if _fits(lo_lines, h, max_lines):
            best = lo_lines
            for _ in range(SHRINK_MAX_ITER):
                if (hi - lo) * base <= SHRINK_PRECISION_PT:
                    break
                mid = (lo + hi) / 2
                mid_lines = run(mid)
                if _fits(mid_lines, h, max_lines):
                    lo, best = mid, mid_lines
                else:
                    hi = mid
            lines, scale = best, lo
        else:
            lines, scale = lo_lines, lo
            mode = "ellipsis"
            warnings.append("TEXT_OVERFLOW")

    end = lines[-1]["_end"]
    real = [ln for ln in lines if "_line" in ln]
    truncated = False
    if auto == "width":
        content_w = max((ln["width"] for ln in real), default=0.0)
        for ln in real:
            para = paragraphs[ln["paragraph"]]
            _realign(ln, content_w, para.get("align", "left"), float(para.get("indent", 0) or 0))
        visible = real
        height = end
        width_out = r3(content_w)
    else:
        width_out = r3(w)
        visible = real
        if max_lines is not None and len(visible) > max_lines:
            visible = visible[:max_lines]
            truncated = True
        if auto == "none":
            kept: list[dict[str, Any]] = []
            for ln in visible:
                if ln["baseline"] + ln["descent"] <= h + EPS:
                    kept.append(ln)
                else:
                    break
            if len(kept) < len(visible):
                truncated = True
            visible = kept
        if truncated and visible and (mode == "ellipsis" or box.get("ellipsis")):
            last = visible[-1]
            para = paragraphs[last["paragraph"]]
            indent = float(para.get("indent", 0) or 0)
            last["_indent"] = indent if last["_line"].first else 0.0
            new_last = _ellipsize(last, w, kerning)
            _realign(new_last, w, para.get("align", "left") if para.get("align") != "justify" else "left", indent)
            visible[-1] = new_last
        if truncated and "TEXT_OVERFLOW" not in warnings:
            warnings.append("TEXT_TRUNCATED")
        if truncated and visible:
            height = r3(visible[-1]["top"] + visible[-1]["height"])
        elif truncated:
            height = 0.0
        else:
            height = end
    offset = 0.0
    if auto == "none":
        valign = box.get("verticalAlign", "top")
        if valign == "middle":
            offset = max(0.0, (h - height) / 2)
        elif valign == "bottom":
            offset = max(0.0, h - height)
    out_lines = []
    for ln in visible:
        out_lines.append(
            {
                "paragraph": ln["paragraph"],
                "top": r3(ln["top"] + offset),
                "baseline": r3(ln["baseline"] + offset),
                "height": ln["height"],
                "x": ln["x"],
                "width": ln["width"],
                "wordSpacing": ln["wordSpacing"],
                "text": ln["text"],
                "runs": ln["runs"],
            }
        )
    return {
        "width": width_out,
        "height": r3(height),
        "scale": round(scale, 6),
        "truncated": truncated,
        "warnings": warnings,
        "lines": out_lines,
    }
