#!/usr/bin/env python3
from __future__ import annotations
import copy, importlib.util, json
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
spec=importlib.util.spec_from_file_location("adapter",Path(__file__).with_name("validate_novel_to_short_drama_adapter.py"))
mod=importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
base=json.loads((ROOT/"references"/"novel-to-short-drama-adapter-test-fixture.json").read_text(encoding="utf-8"))

def run(name, mut=None, expected=None):
    d=copy.deepcopy(base)
    if mut: mut(d)
    errs=mod.validate(d)
    ok=(not errs) if expected is None else any(expected in x for x in errs)
    return {"name":name,"status":"PASS" if ok else "FAIL","errors":errs,"expected":expected}

def second_controller(d): d["controller"]="novel-short-master"
def new_ir(d): d["creates_new_ir"]=True
def owns_truth(d): d["owns_story_truth"]=True
def no_scope(d): d["rights_gate"]["supplied_scope"]=""
def unauthorized_full(d):
    d["rights_gate"]["source_owner_status"]="UNKNOWN_OR_UNAUTHORIZED"
    d["rights_gate"]["permitted_operation"]="FULL_ADAPTATION"
def orphan(d): d["source_episode_allocation"]["episode_units"][0]["source_ids"]=[]
def unknown_source(d): d["source_episode_allocation"]["episode_units"][0]["source_ids"]=["SRC-X"]
def bad_hook(d): d["reward_ledger"]["hook_source"]="RANDOM_NEW_SECRET"
def fake_claim(d): d["release_claim"]="BETTER_THAN_EXTERNAL"
def aux_overload(d): d["active_auxiliaries_count"]=3
def no_payoff(d): d["reward_ledger"]["payoff_event"]=""
def bad_operation(d): d["operations"][0]["type"]="COPY_VERBATIM"

cases=[
    run("positive_adapter"),
    run("reject_second_controller",second_controller,"controller must remain juben"),
    run("reject_new_ir",new_ir,"must not create a new IR"),
    run("reject_story_truth_owner",owns_truth,"must not own story truth"),
    run("reject_missing_source_scope",no_scope,"missing supplied source scope"),
    run("reject_unauthorized_full_adaptation",unauthorized_full,"unauthorized source cannot receive full adaptation"),
    run("reject_orphan_source",orphan,"orphaned source unit"),
    run("reject_unknown_source",unknown_source,"unknown source_id"),
    run("reject_random_hook",bad_hook,"hook must arise"),
    run("reject_fake_claim",fake_claim,"release claim exceeds evidence"),
    run("reject_auxiliary_overload",aux_overload,"active auxiliary budget exceeded"),
    run("reject_hook_without_payoff",no_payoff,"missing reward field: payoff_event"),
    run("reject_invalid_operation",bad_operation,"invalid adaptation operation"),
]
status="PASS" if all(x["status"]=="PASS" for x in cases) else "FAIL"
print(json.dumps({"status":status,"passed":sum(x["status"]=="PASS" for x in cases),"total":len(cases),"results":cases},ensure_ascii=False,indent=2))
raise SystemExit(0 if status=="PASS" else 1)
