"""Render the source PDF with the Set-of-Mark bounding boxes drawn on it.

Runs the Set-of-Mark engine (the default extractor) to get the tables, then
hands them to quber.review for rendering -- the same renderer the
`quber extract --review` flag uses. Each table's som_region is drawn onto its
page with a small ordinal+title label, saved as an annotated copy of the PDF.
Run from the project root with the project venv active.

Usage: python boxed_pdf.py <out_dir> <backend> <pdf> [<pdf> ...]
  backend: api (real LLM correction) or mock (no-LLM). Output is written to
  <out_dir>/<name>.boxed.pdf
"""

from __future__ import annotations

import sys
import traceback
from pathlib import Path
from typing import cast

from quber.agents.llm_client import Backend, get_llm_client
from quber.core.extractors import SetOfMarkExtractor
from quber.review import render_annotated_pdf


def main():
    out_dir, backend = Path(sys.argv[1]), sys.argv[2]
    pdfs = [Path(p) for p in sys.argv[3:]]

    extractor = SetOfMarkExtractor(dpi=200, llm=get_llm_client(cast(Backend, backend)))
    for pdf in pdfs:
        try:
            tables = extractor.extract_tables_sync(pdf)
            out = render_annotated_pdf(tables, pdf, out_dir / f"{pdf.stem}.boxed.pdf")
            boxed = sum(1 for t in tables if t.som_region)
            print(f"OK {pdf.name}: {boxed} boxes -> {out}")
        except Exception as exc:
            traceback.print_exc()
            print(f"FAILED {pdf.name}: {exc}")


if __name__ == "__main__":
    main()
