"""Diagnostic: where does page-2's June "Visa Inc." total row get lost?

Runs the REAL grid locator on page 2 of the Visa PDF, then walks the same
post-processing stages locate() runs (flags_to_located -> pad_boxes ->
declash_stacked), printing each box in PDF points so we can see at which
stage the June table's bottom is pulled up above its own total row.

Read-only: imports prod functions, mutates nothing under src/.
"""

from __future__ import annotations

import asyncio
import tempfile
from pathlib import Path

import fitz

from quber.agents.completeness import page_words
from quber.agents.grid_locator import (
    BOX_PAD_PTS,
    PydanticAIGridLocator,
    declash_stacked,
    flags_to_located,
    overlay_grid,
    pad_boxes,
)

SRC = Path(".cache/s3/qubera-docs/tmus/Q1FY26-Visa-Operational-Performance-Data.pdf")
PAGE = 2
DPI = 200


def render(page_path: Path) -> tuple[Path, float, float]:
    doc = fitz.open(str(SRC))
    try:
        pg = doc[PAGE - 1]
        w, h = pg.rect.width, pg.rect.height
        pix = pg.get_pixmap(dpi=DPI)
        pix.save(str(page_path))
    finally:
        doc.close()
    return page_path, w, h


def show(tag: str, located, page_h: float) -> None:
    print(f"\n=== {tag} (top-origin PDF points) ===")
    for t in located:
        _x0, y0, _x1, y1 = t.region
        print(
            f"  ord{t.ordinal} rows{getattr(t,'grid_rows','?')} "
            f"top={y0*page_h:7.1f}  bottom={y1*page_h:7.1f}  "
            f"tightened={getattr(t,'tightened','?')}  title={t.title!r}"
        )


async def main() -> None:
    loc = PydanticAIGridLocator()
    with tempfile.TemporaryDirectory() as tmp:
        page_png, page_w, page_h = render(Path(tmp) / "page2.png")
        gridded = Path(tmp) / "gridded.png"
        overlay_grid(page_png, gridded, loc.rows, loc.cols)
        from pydantic_ai import BinaryContent

        image = BinaryContent(data=gridded.read_bytes(), media_type="image/png")
        result = await loc.run_locator_with_retry(image, PAGE)
        flags = result.output.tables

    _page_w2, page_h2, words = page_words(SRC, PAGE)
    assert abs(page_h2 - page_h) < 1

    print("MODEL GRID FLAGS (raw):")
    for f in flags:
        print(
            f"  ord{f.ordinal} rows {f.row_start}..{f.row_end} "
            f"cols {f.col_start}..{f.col_end}  title={f.title!r}"
        )
    print(f"\ngrid: {loc.rows} rows over {page_h:.0f}pt -> {page_h/loc.rows:.1f}pt/row")
    print("reference y (top-origin): International=248.5  VisaInc total=259.9  March title=279.2")

    located = flags_to_located(flags, words, page_w, page_h, loc.rows, loc.cols)
    show("after flags_to_located (tighten)", located, page_h)
    padded = pad_boxes(located, page_w, page_h, BOX_PAD_PTS)
    show("after pad_boxes", padded, page_h)
    declashed = declash_stacked(padded, words, page_w, page_h)
    show("after declash_stacked", declashed, page_h)


if __name__ == "__main__":
    asyncio.run(main())
