"""Experiment: feed each visual bounding box to Camelot as its extraction area.

For every visual table, convert its full-anatomy box to a Camelot
`table_areas` string and run a region-constrained stream pass. This forces a
1:1 mapping (one Camelot grid per visual table), so Camelot can neither
shatter one table into many nor merge many into one — the region is dictated
by vision. Prints, per visual table, the guided grid's shape/accuracy next to
the unguided Camelot count on that page.
"""

from __future__ import annotations

import json
import sys
from pathlib import Path

import fitz

from quber.core.extractors.camelot.correspondence.geometry import norm_bbox_to_table_area
from quber.core.extractors.camelot.correspondence.recovery import camelot_targeted


def run(dual_json: Path, source: Path, pages: list[int]) -> None:
    data = json.loads(dual_json.read_text())
    doc = fitz.open(str(source))

    visual_by_page: dict[int, list] = {}
    for v in data["visual"]:
        visual_by_page.setdefault(v["page"], []).append(v)
    unguided_by_page: dict[int, int] = {}
    for c in data["camelot"]:
        p = c["candidate"]["page"]
        unguided_by_page[p] = unguided_by_page.get(p, 0) + 1

    for page in pages:
        w, h = doc[page - 1].rect.width, doc[page - 1].rect.height
        vtables = sorted(visual_by_page.get(page, []), key=lambda v: v["ordinal"])
        print(f"\n{'='*78}\nPAGE {page}: visual={len(vtables)} tables | unguided camelot={unguided_by_page.get(page, 0)} grids")
        for v in vtables:
            area = norm_bbox_to_table_area(tuple(v["region"]), w, h)
            try:
                cand = camelot_targeted(str(source), page, area, v["ordinal"])
            except Exception as exc:
                print(f"  V{v['ordinal']} {v['title'][:40]!r}: camelot raised {exc}")
                continue
            if cand is None:
                print(f"  V{v['ordinal']} {v['title'][:40]!r}: camelot found nothing in region")
                continue
            rows = len(cand.cells)
            cols = max((len(r) for r in cand.cells), default=0)
            print(f"  V{v['ordinal']} {v['title'][:40]!r}: guided grid {rows}x{cols} acc={cand.accuracy:.0f}")
            preview = "\n".join("      " + " | ".join(c.strip() for c in row) for row in cand.cells[:4])
            print(preview)


def main() -> None:
    jobs = "/home/mande/.claude/jobs/a95a5f59/tmp"
    targets = {
        "daloopa": (f"{jobs}/93239979.dual.json", ".cache/s3/qubera-docs/daloopa/93239979/93239979.pdf",
                    [10, 23, 11]),
        "bhe": (f"{jobs}/BHE_991.dual.json", "documents/BHE_991.pdf", [1, 2]),
    }
    which = sys.argv[1] if len(sys.argv) > 1 else "daloopa"
    js, pdf, pages = targets[which]
    run(Path(js), Path(pdf), pages)


if __name__ == "__main__":
    main()
