"""계약 견본(contract/) 12개를 합성 자료로 다시 만든다. 실제 고객 자료는 쓰지 않는다.

실행: cd workers/case-report && <python> scripts/gen_contract.py
견본은 세 담당(워커·서버·사이트)이 같이 읽는 형상 기준이다. 형상이 바뀌면 이 스크립트로 다시 만들고 차이를 보고한다.
"""
import json
import subprocess
import sys
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path[:0] = [str(ROOT), str(ROOT / "tests")]

import synth  # noqa: E402
from pdfgen import make_pdf  # noqa: E402

from case_report import analyze, revalidate  # noqa: E402
from case_report.cli import version_envelope  # noqa: E402

OUT = ROOT / "contract"


def dump(name, obj):
    (OUT / name).write_text(json.dumps(obj, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")


def cli(cmd, inp, tmp, password=None):
    ip, op = Path(tmp) / f"{cmd}-in.json", Path(tmp) / f"{cmd}-out.json"
    ip.write_text(json.dumps(inp, ensure_ascii=False), encoding="utf-8")
    args = [sys.executable, "-m", "case_report.cli", cmd, "--in", str(ip), "--out", str(op)] + (["--password-stdin"] if password else [])
    subprocess.run(args, cwd=ROOT, input=(password + "\n") if password else "", text=True, capture_output=True, check=False)
    return json.loads(op.read_text(encoding="utf-8"))


def extract_input(tmp, pdf, **kw):
    inp = {"schema": "case-report.extract-input/1", "file_id": synth.fid(9), "pdf_path": str(pdf), "password_stdin": False, "read_mode": "auto",
           "ocr_dpi": 300, "kind_hint": None, "reader_hint": None, "cache_dir": str(Path(tmp) / "cache"), "tmp_dir": str(Path(tmp) / "tmp"),
           "limits": {"max_pages": 60, "page_timeout_s": 120}}
    inp.update(kw)
    return inp


def main():
    OUT.mkdir(exist_ok=True)
    v = version_envelope()
    v["python"] = "3.12.3"
    v["ocr"]["models_present"] = False
    dump("version.ok.json", v)
    ci, st, _ = synth.base_docs()
    dump("extract.ok.credit-info.json", ci)
    dump("extract.ok.statement-precise.json", st)
    gen = synth.stmt_env(4, "삼성화재", "GENERIC", visits=[synth.visit("2025-02-19", "2025-02-19", "합성의원", "OUTPATIENT", 20000, confirmed=False)],
                         payments=[synth.payment("질병통원의료비", 20000, "2025-03-02", confirmed=False)], scope_kind="UNKNOWN", pages_complete=None,
                         contract_scope="UNKNOWN")
    dump("extract.partial.statement-generic.json", gen)
    with tempfile.TemporaryDirectory() as tmp:
        enc = Path(tmp) / "enc.pdf"
        enc.write_bytes(make_pdf([(40, 800, "기본진료정보"), (40, 780, "성명 김합성")], password="synthetic-pw"))
        dump("extract.needs-password.json", _no_timing(cli("extract", extract_input(tmp, enc), tmp)))
        bad = Path(tmp) / "bad.pdf"
        bad.write_bytes(b"not a pdf at all")
        dump("extract.failed.json", _no_timing(cli("extract", extract_input(tmp, bad), tmp)))
        unk = Path(tmp) / "unknown.pdf"
        unk.write_bytes(make_pdf([(40, 800 - 14 * i, "Synthetic unrelated document line number %d with enough text" % i) for i in range(6)]))
        dump("extract.unsupported.json", _no_timing(cli("extract", extract_input(tmp, unk), tmp)))
        src = Path(tmp) / "ci.json"
        src.write_text(json.dumps(ci, ensure_ascii=False), encoding="utf-8")
        dump("revalidate.edit-invalid.json", revalidate.run({"schema": "case-report.revalidate-input/1", "file_id": ci["file"]["file_id"],
                                                             "extraction_path": str(src),
                                                             "edits": [{"op": "replace", "path": "/data/silson_rows/0/start", "value": "2025/01"}]}))
        r1 = analyze.run(synth.scenario_round1(Path(tmp) / "r1"))
        dump("analyze.ok.round1.json", r1)
        dump("analyze.ok.round2.json", analyze.run(synth.scenario_round2(Path(tmp) / "r2", r1)))
        dump("analyze.blocked.json", analyze.run(synth.scenario_blocked(Path(tmp) / "b")))
        bad_in = synth.scenario_round1(Path(tmp) / "f")
        Path(bad_in["documents"][0]["extraction_path"]).write_text("{}", encoding="utf-8")  # sha256 불일치 → INPUT_INVALID
        dump("analyze.failed.json", cli("analyze", bad_in, tmp))
    print("\n".join(sorted(p.name for p in OUT.glob("*.json"))))


def _no_timing(env):
    env["timing"] = {"total_ms": 0, "pages": [{"page": 1, "mode": "text", "ms": 0, "chars": 0}]} if env["timing"]["pages"] else {"total_ms": 0, "pages": []}
    return env


if __name__ == "__main__":
    main()
