#!/usr/bin/env python3
from __future__ import annotations
import json, sys
from pathlib import Path

ALLOWED_RIGHTS={"USER_ORIGINAL","USER_AUTHORIZED","PUBLIC_DOMAIN","UNKNOWN_OR_UNAUTHORIZED"}
ALLOWED_INPUT={"FULL_NOVEL","CHAPTER_RANGE","SINGLE_CHAPTER","FRAGMENT","OUTLINE","USER_SPECIFIED_EPISODES"}
ALLOWED_OPS={"KEEP","DELETE","MERGE","REORDER","FRONTLOAD","EXTERNALIZE","CONDENSE","BRIDGE","ORIGINALIZE"}
ALLOWED_HOOK={"CONSEQUENCE_OF_EPISODE","PREPLANTED_THREAD"}
FORBIDDEN_CLAIMS={"BETTER_THAN_EXTERNAL","PROFESSIONAL_PASSED","PRODUCTION_READY"}

def validate(d):
    e=[]
    if d.get("controller")!="juben": e.append("controller must remain juben")
    if d.get("controller_count")!=1: e.append("controller_count must equal 1")
    if d.get("role")!="SOURCE_TO_EPISODE_ADAPTER": e.append("invalid adapter role")
    if d.get("creates_new_ir") is not False: e.append("adapter must not create a new IR")
    if d.get("owns_story_truth") is not False: e.append("adapter must not own story truth")
    if not 0 <= d.get("active_auxiliaries_count",99) <= 2: e.append("active auxiliary budget exceeded")
    rights=d.get("rights_gate",{})
    if rights.get("source_owner_status") not in ALLOWED_RIGHTS: e.append("invalid rights status")
    if not rights.get("supplied_scope"): e.append("missing supplied source scope")
    if rights.get("source_owner_status")=="UNKNOWN_OR_UNAUTHORIZED" and rights.get("permitted_operation")=="FULL_ADAPTATION":
        e.append("unauthorized source cannot receive full adaptation")
    router=d.get("input_router",{})
    if router.get("mode") not in ALLOWED_INPUT: e.append("invalid input mode")
    allocation=d.get("source_episode_allocation",{})
    source_ids={x.get("source_id") for x in allocation.get("source_units",[]) if x.get("source_id")}
    if not source_ids: e.append("source allocation must contain source units")
    eps=allocation.get("episode_units",[])
    if not eps: e.append("source allocation must contain episode units")
    used=set()
    for ep in eps:
        for k in ["episode_id","local_question","local_payoff","series_delta","exit_pressure"]:
            if not ep.get(k): e.append("missing episode allocation field: "+k)
        for sid in ep.get("source_ids",[]):
            if sid not in source_ids: e.append("episode references unknown source_id")
            used.add(sid)
    if source_ids-used: e.append("orphaned source unit must be explicitly resolved")
    cap=d.get("capacity_estimate",{})
    if not isinstance(cap.get("duration"),(int,float)) or cap["duration"]<=0: e.append("duration must be positive")
    for op in d.get("operations",[]):
        if op.get("type") not in ALLOWED_OPS: e.append("invalid adaptation operation")
        if not op.get("creative_decision"): e.append("operation requires creative decision")
    reward=d.get("reward_ledger",{})
    for k in ["episode_id","promise","payoff_mode","payoff_event","next_pressure","hook_source"]:
        if not reward.get(k): e.append("missing reward field: "+k)
    if reward.get("hook_source") not in ALLOWED_HOOK: e.append("hook must arise from episode consequence or preplanted thread")
    if d.get("release_claim") in FORBIDDEN_CLAIMS: e.append("release claim exceeds evidence")
    return e

def main():
    p=Path(sys.argv[1] if len(sys.argv)>1 else "references/novel-to-short-drama-adapter-test-fixture.json")
    d=json.loads(p.read_text(encoding="utf-8"))
    e=validate(d)
    print(json.dumps({"status":"PASS" if not e else "FAIL","errors":e},ensure_ascii=False,indent=2))
    return 0 if not e else 1

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