"""사람이 장부의 `uncertain` 줄을 매듭짓는다 — 「보내기 전에 거절됐다(안 샀다)」일 때만.

    python tools/grounding_audit/settle_uncertain.py --run-id RID --journal replay --identity <앞글자> \
        --why "22:08 로그: research_call_budget 초과 40/40 · 거절한 자리 llm_client._completion — provider 앞" \
        --by "claude(사용자 위임)"

★증거 없이 쓰지 마라. 「샀다」는 여기서 못 정한다(답이 없으니 다시 사야 한다).
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--run-id", required=True)
    ap.add_argument("--journal", choices=("central", "replay"), required=True)
    ap.add_argument("--identity", required=True, help="신원 앞글자(유일해야 한다)")
    ap.add_argument("--why", required=True)
    ap.add_argument("--by", required=True)
    a = ap.parse_args()
    sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
    from tools.grounding_audit import canary_isolation as ci
    from app.modules.pipeline.grounding_chunk_journal import ChunkJournal
    root = ci.root_dir(a.run_id)
    name = "journal.json" if a.journal == "central" else "journal_replay.json"
    paths = list(root.glob(f"projects/*/checkpoints/episodes/*/reference_acquisition/{name}"))
    if len(paths) != 1:
        print("장부를 하나로 못 찾았다:", paths); return 2
    raw = json.loads(paths[0].read_text(encoding="utf-8"))
    hits = [c["identity"] for c in raw.get("calls") or [] if str(c.get("identity", "")).startswith(a.identity)]
    if len(hits) != 1:
        print("신원이 하나로 안 잡힌다:", hits); return 2
    jr = ChunkJournal(paths[0], contract=raw.get("contract") or {})
    got = jr.settle_uncertain(hits[0], bought=False, why=a.why, decided_by=a.by)
    print("매듭:", json.dumps({k: got[k] for k in ("identity", "status", "decision")}, ensure_ascii=False))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
