"""Implied font 9 advances from the fill-and-V round (Allegro 2, 2026-11-21 16:39-17:10).

Copy it and fit_widths.py.txt as .py beside ../lines.json and run it with the build the labels were
printed from (83272f6) first on PYTHONPATH:
    PYTHONPATH=<83272f6 checkout>/src python fit_fill.py FILL_DIR [--json OUT] [--tables OUT]

Each row is char * N + "M", right-aligned at x 95 mm, with five vertical lines 0.5 mm apart through the
final M. A line record starts at its column and is one unit (2 dots) wide, so its middle is
column * 2 + 1 dots. The reading r (lines, + = the final M should move right) puts the M's ink middle at
the middle line's middle less 4 r dots (the lines lie 2 units, 4 dots, apart). The glyphs print
SHIFT dots right of the text record's column (30 pt: 2, else 0), and an M's ink middle lies
(llx + urx) / 2 = 417 / 1000 em right of its origin (Helvetica-Bold AFM: B 69 0 765 718). So the N
characters reach
    P = middle_line * 2 + 1 - 4 r - text_column * 2 - SHIFT - 0.417 em
dots, and each advances P / N. Both columns are read from the rendered records, not from x.
"""

from __future__ import annotations

import json
import re
import sys
from pathlib import Path

from datamax_dpl.domain.label import Label
from datamax_dpl.domain.render import build_job
from datamax_dpl.domain.render_context import RenderOptions

DOTS_PER_UNIT = 2
DOTS_PER_LINE = 4
SHIFT = {30: 2}
M_INK_MIDDLE = (69 + 765) / 2 / 1000
TEXT = re.compile(rb"^19[1-9A-O][1-9A-O][0-9A-Za-z]{3}(\d{4})(\d{4})(.*)$")
LINE = re.compile(rb"^1X11000(\d{4})(\d{4})l\d{3}(\d{3})$", re.IGNORECASE)


def rows(fill: Path) -> list[tuple[int, int, str, int]]:
    out = []
    for line in (fill / "README.txt").read_text(encoding="utf-8").splitlines():
        m = re.match(r"line +(\d+) +(\d+) pt +char '(.)' \(byte \d+\) +N=(\d+)", line)
        if m:
            out.append((int(m[1]), int(m[2]), m[3], int(m[4])))
    return out


def readings(fill: Path) -> list[tuple[float, ...]]:
    """Every row's readings, label by label, bottom row first.

    A row has its label's reading, then that of each recheck: a line ``fNN-recheck ...: values`` is
    a reprint of label fNN's stored job, read again, its values in the same row order.
    """
    first: dict[str, list[float]] = {}
    again: dict[str, list[list[float]]] = {}
    for line in (fill / "readings.txt").read_text(encoding="utf-8").splitlines():
        label = line.split(" ", 1)[0]
        body = line.split("[", 1)[0].rsplit(": ", 1)[1]
        values = [float(v.replace(",", ".")) for v in body.split()]
        if label.endswith("-recheck"):
            again.setdefault(label.removesuffix("-recheck"), []).append(values)
        else:
            first[label] = values
    assert set(again) <= set(first), sorted(set(again) - set(first))
    out: list[tuple[float, ...]] = []
    for label, values in first.items():
        reprints = again.get(label, [])
        assert all(len(more) == len(values) for more in reprints), label
        out.extend(zip(values, *reprints))
    return out


def columns(fill: Path) -> list[tuple[str, int, int]]:
    """(label, text column, middle line column) of every row, label by label, bottom row first."""
    found: list[tuple[str, int, int]] = []
    for path in sorted(fill.glob("f*.json")):
        result = build_job(Label.model_validate_json(path.read_bytes()), RenderOptions(model="allegro-2"))
        assert result.ok, (path, result.findings)
        records = result.data.split(b"\r")
        for i, record in enumerate(records):
            text = TEXT.match(record)
            if not text or not text.group(3).endswith(b"M"):
                continue
            lines = [LINE.match(r) for r in records[i + 1 : i + 6]]
            assert all(lines), records[i + 1 : i + 6]
            # The middle line reaches further, so its record starts lower (a smaller row) and is taller.
            middle = min(lines, key=lambda m: int(m.group(1)))  # type: ignore[union-attr]
            found.append((f"fill/{path.name}", int(text.group(2)), int(middle.group(2))))  # type: ignore[union-attr]
    return found


#: The 30 pt advances the line-end record (../lines.json, read to 0.1 mm over 9 to 24 characters)
#: already measured, finer than this round's half line over 8 to 28: they keep the value fit_widths
#: fits to those lines, unrounded.
LINE_END_30_PT = set("M0123456789,./ STKBOX")


def tables(fill: dict[tuple[int, str], float]) -> dict[int, dict[int, float]]:
    """Per printed size, the advance in dots of each byte the round measured, to a millionth of a dot.

    ``fill`` holds this round's unrounded advance per (size, character). 12 pt and the line-end
    30 pt advances come from the line-end fit (fit_widths.fit over ../lines.json): at 12 pt each
    character's fitted width at that em, which a character measured at 12 pt only has as its whole
    dots and "/" has as its width, not the 11 dots its 12 pt line gave (the model keeps that apart,
    for 203 dpi at 12 pt only). Nothing is rounded before the last step, which keeps 6 decimals.
    """
    from fit_widths import fit  # beside this script, beside ../lines.json

    widths, _ = fit()
    chars = sorted({char for _, char in fill})
    byte = {char: char.encode("cp850")[0] for char in chars}
    exact: dict[int, dict[int, float]] = {12: {}, 18: {}, 24: {}, 30: {}}
    for char in chars:
        exact[12][byte[char]] = widths[byte[char]] * em(12) / 1000
        exact[18][byte[char]] = fill[18, char]
        exact[24][byte[char]] = fill[24, char]
        exact[30][byte[char]] = widths[byte[char]] * em(30) / 1000 if char in LINE_END_30_PT else fill[30, char]
    return {points: {code: round(value, 6) for code, value in row.items()} for points, row in exact.items()}


def em(points: int) -> float:
    return points * 203 / 72


def main() -> int:
    fill = Path(sys.argv[1])
    table, values, cols = rows(fill), readings(fill), columns(fill)
    assert len(table) == len(values) == len(cols) == 164, (len(table), len(values), len(cols))
    out = []
    fill: dict[tuple[int, str], float] = {}
    for (number, points, char, count), read, (label, text_column, line_column) in zip(table, values, cols):
        # A label printed and read twice takes the mean: the advance is linear in the reading, so it is
        # the mean of the two advances, each reading as good as the other.
        reading = sum(read) / len(read)
        reached = (
            line_column * DOTS_PER_UNIT + 1 - DOTS_PER_LINE * reading
            - text_column * DOTS_PER_UNIT - SHIFT.get(points, 0) - M_INK_MIDDLE * em(points)
        )
        fill[points, char] = reached / count
        out.append({
            "line": number, "label": label, "points": points, "char": char, "count": count, "reading": reading,
            "text_column": text_column, "line_column": line_column, "reached_dots": round(reached, 3),
            "advance_dots": round(reached / count, 4), "resolution_dots": round(2 / count, 4),
            **({"readings": list(read)} if len(read) > 1 else {}),
        })
    for row in out:
        print("{line:4d} {points:3d} {char!r:4} {count:3d} {reading:5.1f} col {text_column:4d} mid {line_column:4d} "
              "reached {reached_dots:8.2f} advance {advance_dots:7.3f} +/- {resolution_dots:.3f}".format(**row))
    if "--tables" in sys.argv:
        Path(sys.argv[sys.argv.index("--tables") + 1]).write_text(
            json.dumps(tables(fill), indent=1, sort_keys=True) + "\n", encoding="utf-8"
        )
    if "--json" in sys.argv:
        Path(sys.argv[sys.argv.index("--json") + 1]).write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8")
    return 0


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