"""Preserve every playground document's scan-output JSONs to S3.

For each row in ade_playground.documents, uploads the RAG input artifacts
(unified parse, tables, fusion report, scanned tables, figures, charts, and
the ADE parse where one exists) to <dest>/<original-filename-stem>/, keeping
the hash-keyed names inside the folder so the files tie back to the library's
content identity. Idempotent: aws s3 cp overwrites, so a re-run refreshes the
preservation copy. Read-only against the database; never touches the PDFs.

Run with `uv run python` from the repository root so quber.settings resolves.
"""

from __future__ import annotations

import argparse
import subprocess
import sys

from quber.playground import db
from quber.settings import get_settings

SUFFIXES = [
    ".unified.json",
    ".tables.json",
    ".fusion.json",
    ".scanned-tables.json",
    ".figures.json",
    ".charts.json",
    ".ade.json",
]


def main() -> int:
    p = argparse.ArgumentParser(description="Preserve scan-output JSONs for every library document to S3.")
    p.add_argument(
        "--dest",
        default="s3://qubera-docs/rj.reit/scan-output",
        help="destination S3 prefix (per-document folders are created beneath it)",
    )
    p.add_argument("--dry-run", action="store_true", help="print what would upload and exit")
    args = p.parse_args()

    data_dir = get_settings().playground.data_dir
    with db.connect() as conn:
        rows = conn.execute(
            "SELECT doc_key, filename, folder FROM ade_playground.documents ORDER BY folder, filename"
        ).fetchall()

    uploaded = missing_docs = 0
    for doc_key, filename, folder in rows:
        present = [data_dir / f"{doc_key}{s}" for s in SUFFIXES if (data_dir / f"{doc_key}{s}").exists()]
        if not present:
            print(f"NO ARTIFACTS on disk for {filename} ({doc_key}) — nothing to preserve")
            missing_docs += 1
            continue
        stem = filename.rsplit("/", 1)[-1].rsplit(".", 1)[0]
        prefix = f"{args.dest}/{stem}"
        for path in present:
            if args.dry_run:
                print(f"would upload {path.name} -> {prefix}/")
            else:
                subprocess.run(["aws", "s3", "cp", str(path), f"{prefix}/{path.name}", "--quiet"], check=True)
            uploaded += 1
        print(f"{folder or '-':5s} {filename}: {len(present)} files -> {prefix}/")

    verb = "would preserve" if args.dry_run else "preserved"
    print(f"\n{verb} {uploaded} files for {len(rows) - missing_docs}/{len(rows)} documents")
    if missing_docs:
        print(f"{missing_docs} documents had no artifacts on disk — listed above, not silently dropped")
    return 0


if __name__ == "__main__":
    sys.exit(main())
