"""Set-of-Mark extraction review HTML: per table, a before/after side by side.

Left ("before"): the page cropped around the table with its Set-of-Mark
bounding box (the model's som_region) drawn on it. Right ("after"): the final
corrected markdown. No intermediary raw camelot grid.

Runs the Set-of-Mark engine live (the default extractor) to get the tables,
then hands them to quber.review for rendering -- the same renderer the
`quber extract --review` flag uses. Run from the project root with the project
venv active.

Usage: python gen_html.py <out.html> <backend> <pdf> [<pdf> ...]
  backend: api (real LLM correction) or mock (no-LLM, raw grid markdown).
The output is responsive: on screens <=900px the two columns stack.
"""

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_review_html


def main():
    out, backend = 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)))

    items = []
    for pdf in pdfs:
        try:
            tables = extractor.extract_tables_sync(pdf)
        except Exception as exc:
            traceback.print_exc()
            print(f"FAILED {pdf.stem}: {exc}")
            continue
        print(f"OK {pdf.stem}: {len(tables)} tables")
        items.append((pdf, tables))

    render_review_html(items, Path(out))
    print(f"wrote {out} ({Path(out).stat().st_size // 1024} KB)")


if __name__ == "__main__":
    main()
