#!/usr/bin/env python3
"""Validate one adjudication label and append it to <agent>/labels.jsonl. The only way labels are written.

  python append_label.py a1 <<'EOF'
  {"packet_id": "...", "flag": "none", ...}
  EOF

The verdict is derived from the flag here (fail iff the flag is in the fail set), so it can never disagree with it.
Rejects: unknown packet id for this agent's slice, a packet id already labelled (pass --replace to supersede it; the
old line is kept and marked superseded), unknown enum values, a missing score on a dimension-score row, a reason over
400 characters, a quote over 25 words.
"""
import json
import sys
from datetime import datetime, timezone
from pathlib import Path

ADJ = Path(__file__).resolve().parent
FLAGS = {"none": False, "claim_overspecification_minor": False, "claim_unsourced_minor": False,
         "dim_disagreement_minor": False, "dim_disagreement_major": True, "contradicted_fact": True,
         "fabricated_or_unsupported_claim": True}
ENUMS = {"supported_by_cited_source": {"yes", "partly", "no", "source_unreadable"},
         "true_per_web": {"true", "false", "unknown", "not_checked"},
         "confidence": {"high", "medium", "low"}}
CHECKED = {"evidence_window", "saved_page", "live_url", "web_search", "rubric", "bundle_evidence"}


def main():
    agent = sys.argv[1]
    replace = "--replace" in sys.argv
    rows = {json.loads(x)["packet_id"]: json.loads(x) for x in
            (ADJ / "inputs" / f"slice_{agent}.jsonl").read_text(encoding="utf-8").split("\n") if x.strip()}
    lab = json.loads(sys.stdin.read())
    pid = lab.get("packet_id")
    err = []
    if pid not in rows:
        err.append(f"packet_id {pid!r} is not in slice_{agent}")
    if lab.get("flag") not in FLAGS:
        err.append(f"flag must be one of {sorted(FLAGS)}")
    for k, allowed in ENUMS.items():
        if lab.get(k) not in allowed:
            err.append(f"{k} must be one of {sorted(allowed)}")
    ch = lab.get("checked")
    if not isinstance(ch, list) or not ch or not set(ch) <= CHECKED:
        err.append(f"checked must be a non-empty list drawn from {sorted(CHECKED)}")
    if len(str(lab.get("reason", ""))) > 400 or not lab.get("reason"):
        err.append("reason is required and at most 400 characters")
    if len(str(lab.get("quote", "")).split()) > 25:
        err.append("quote is at most 25 words")
    if pid in rows and rows[pid]["section"] == "Dimension scores":
        if not isinstance(lab.get("adj_raw_score"), int) or not isinstance(lab.get("stated_raw_score"), int):
            err.append("dimension-score rows need integer adj_raw_score and stated_raw_score")
    out = ADJ / agent / "labels.jsonl"
    prior = [json.loads(x) for x in out.read_text(encoding="utf-8").split("\n") if x.strip()] if out.exists() else []
    if any(p["packet_id"] == pid and not p.get("superseded") for p in prior) and not replace:
        err.append(f"{pid} already labelled; pass --replace to supersede")
    if err:
        print("REJECTED:\n- " + "\n- ".join(err))
        sys.exit(2)
    if replace:
        prior = [dict(p, superseded=True) if p["packet_id"] == pid else p for p in prior]
    lab["verdict"] = "fail" if FLAGS[lab["flag"]] else "pass"
    lab["agent"] = agent
    lab["labelled_at"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    prior.append(lab)
    out.parent.mkdir(exist_ok=True)
    out.write_text("".join(json.dumps(p, ensure_ascii=False) + "\n" for p in prior), encoding="utf-8")
    done = len({p["packet_id"] for p in prior if not p.get("superseded")})
    print(f"OK {pid} -> {lab['verdict']} ({lab['flag']}); {done}/{len(rows)} labelled")


if __name__ == "__main__":
    main()
