"""Standalone raw-camelot extraction dump for cross-version comparison.

Runs camelot.read_pdf for lattice + stream on one PDF and writes a JSON
record per detected table. Intentionally imports only camelot (no quber
stack) so the exact same script runs under any camelot version, including
an ephemeral `uv run --no-project --with camelot-py==<old>` baseline.

Usage: python raw_extract.py <pdf> <out.json> [extra read_pdf kwargs as k=v]
Numeric/literal values in k=v are parsed (int/float/bool); else string.
"""

import json
import sys
import traceback


def parse_kv(arg):
    k, _, v = arg.partition("=")
    for cast in (int, float):
        try:
            return k, cast(v)
        except ValueError:
            pass
    if v.lower() in ("true", "false"):
        return k, v.lower() == "true"
    return k, v


def table_record(table, flavor):
    raw_page = getattr(table, "page", 1)
    page = int(raw_page) if raw_page is not None else 1
    bbox = list(table._bbox) if getattr(table, "_bbox", None) else None
    report = getattr(table, "parsing_report", {}) or {}
    try:
        cells = [[str(c) for c in row] for row in table.df.values.tolist()]
    except Exception:
        cells = []
    n_rows = len(cells)
    n_cols = max((len(r) for r in cells), default=0)
    non_empty = sum(1 for r in cells for c in r if str(c).strip())
    return {
        "flavor": flavor,
        "page": page,
        "bbox": bbox,
        "accuracy": float(report.get("accuracy", 0.0) or 0.0),
        "confidence": report.get("confidence"),
        "n_rows": n_rows,
        "n_cols": n_cols,
        "n_cells": n_rows * n_cols,
        "n_nonempty": non_empty,
        "cells": cells,
    }


def main():
    import camelot

    pdf, out = sys.argv[1], sys.argv[2]
    extra = dict(parse_kv(a) for a in sys.argv[3:])

    cam_ver = getattr(camelot, "__version__", None)
    if cam_ver is None:
        try:
            from importlib.metadata import version

            cam_ver = version("camelot-py")
        except Exception:
            cam_ver = "?"

    records = []
    errors = {}
    for flavor in ("lattice", "stream"):
        try:
            tables = camelot.read_pdf(pdf, pages="all", flavor=flavor, **extra)
            for t in tables:
                records.append(table_record(t, flavor))
        except Exception as exc:
            errors[flavor] = f"{type(exc).__name__}: {exc}"
            traceback.print_exc()

    result = {
        "pdf": pdf,
        "camelot_version": cam_ver,
        "extra_kwargs": extra,
        "n_tables": len(records),
        "errors": errors,
        "tables": records,
    }
    with open(out, "w") as f:
        json.dump(result, f, indent=2)
    print(f"{pdf}: camelot {cam_ver} -> {len(records)} tables ({out})")


if __name__ == "__main__":
    main()
