#!/usr/bin/env python3
from __future__ import annotations
import json,sys
from pathlib import Path
OVERCLAIMS={"DIALOGUE_TABLE_READ","COMPARATIVE_BLIND_TESTED","HUMAN_REVIEWED","PERFORMANCE_VALIDATED","PRODUCTION_VALIDATED","CROSS_MODEL_BEST"}
EXPECTED={
"thought_policy":"PREVERBAL_AND_PARTIAL_NOT_AUTHOR_REPORT",
"attention_policy":"SELECTIVE_CHARACTER_SPECIFIC_NOT_OBJECTIVE_DUMP",
"action_policy":"IMPULSE_CAN_BE_INHIBITED_TRANSFORMED_OR_DELAYED",
"object_policy":"AFFORDANCE_AND_CONTINUITY_NOT_SYMBOL_LOOKUP",
"interiority_policy":"EVIDENCE_BEFORE_REDUNDANT_EMOTION_NAMING",
"self_knowledge_policy":"CHARACTER_LIMITED_NOT_AUTHOR_OMNISCIENT",
"ordinary_behavior_policy":"ORDINARY_ACTION_MAY_STAY_ORDINARY",
"displacement_policy":"CAUSAL_AND_OPTIONAL_NOT_MANDATORY",
"justification_policy":"POST_HOC_MAY_BE_SINCERELY_WRONG",
"punctuation_policy":"ILLOCUTION_AND_PROSODY_NOT_GRAMMAR_ONLY",
"medium_policy":"NOVEL_AND_SCREENPLAY_DIFFERENT"}
AWARENESS={"NONE","VAGUE","PARTIAL","CLEAR"}
SELF_KNOWLEDGE={"K0","K1","K2","K3","K4"}
SIGNIFICANCE={"LOW","MEDIUM","HIGH"}
JUST={"BELIEVED","PARTLY_BELIEVED","STRATEGIC_LIE","UNKNOWN"}
MEDIUM={"NOVEL","SCREENPLAY"}
PUNCT={"。","？","！","……","——","，","；","："}

def req(e,obj,keys,p):
    for k in keys:
        if k not in obj or obj.get(k) in (None,""): e.append(f"{p} missing: {k}")

def validate(d):
    e=[]
    if d.get("schema")!="JINGHUA-HUMAN-BEHAVIOR-1.0": e.append("schema must be JINGHUA-HUMAN-BEHAVIOR-1.0")
    if d.get("controller")!="juben": e.append("controller must remain juben")
    if d.get("story_truth_owner")!="Creative": e.append("story truth owner must remain Creative")
    if d.get("creates_new_ir") is not False: e.append("human behavior runtime must not create new IR")
    if d.get("stage")!="W5-W7": e.append("human behavior runtime must stay in W5-W7")
    if d.get("scene_lock") is not True: e.append("scene must be locked before behavior realization")
    if d.get("parent_runtime")!="JINGHUA_CHARACTER_REALIZATION": e.append("human behavior runtime must remain a realization layer")
    pol=d.get("runtime_policy",{})
    for k,v in EXPECTED.items():
        if pol.get(k)!=v: e.append(f"{k} must be {v}")

    at=d.get("attention_frame",{})
    req(e,at,["available_scene_facts","noticed_first","noticed_late","ignored_or_missed","attention_reason","wrong_salience","action_changed_by_attention"],"attention_frame")
    avail=set(at.get("available_scene_facts",[]))
    observed=set(at.get("noticed_first",[]))+set() if False else None
    for k in ["noticed_first","noticed_late","ignored_or_missed"]:
        vals=at.get(k,[])
        if any(x not in avail for x in vals): e.append(f"{k} may only use available scene facts")
    if not at.get("noticed_first"): e.append("attention must select at least one noticed fact")

    pr=d.get("preverbal_response",{})
    req(e,pr,["trigger","immediate_orientation","body_change","impulse","awareness_level","first_available_action"],"preverbal_response")
    if pr.get("awareness_level") not in AWARENESS: e.append("invalid preverbal awareness level")

    it=d.get("impulse_transformation",{})
    req(e,it,["impulse","inhibition_source","prohibited_action","replacement_behavior","involuntary_leak","cost_of_control"],"impulse_transformation")

    gap=d.get("action_language_gap",{})
    req(e,gap,["stated_position","behavior_evidence","self_awareness_now","delayed_recognition_point","contradiction_cost"],"action_language_gap")
    if gap.get("self_awareness_now") not in AWARENESS: e.append("invalid action-language self awareness")

    ob=d.get("object_mediated_behavior",{})
    req(e,ob,["object_id","normal_affordance","current_action","action_exceeds_function","psychological_pressure_carried","continuity_effect","story_significance"],"object_mediated_behavior")
    if ob.get("story_significance") not in SIGNIFICANCE: e.append("invalid object story significance")
    if ob.get("story_significance")=="HIGH": e.append("HIGH story-significance object must return to Creative")
    if not ob.get("normal_affordance"): e.append("object behavior requires affordance")

    ds=d.get("displacement",{})
    if ds.get("enabled"):
        req(e,ds,["true_source","forbidden_or_costly_target","displaced_target","surface_complaint","why_this_target_is_safer","collateral_relationship_cost"],"displacement")
        if ds.get("true_source")==ds.get("displaced_target"): e.append("displacement target must differ from true source")

    sj=d.get("self_justification",{})
    req(e,sj,["action_taken","likely_private_driver","conscious_explanation","explanation_sincerity","contradiction_evidence","future_revision_possible"],"self_justification")
    if sj.get("explanation_sincerity") not in JUST: e.append("invalid self justification sincerity")

    br=d.get("behavioral_residue",{})
    req(e,br,["scene_trigger","residue_channel","residue","duration","who_notices","later_echo"],"behavioral_residue")

    ig=d.get("interiority_gate",{})
    req(e,ig,["evidence_already_carries_emotion","proposed_explanation","adds_new_causal_information","character_can_self_name_it","delete_or_keep","reason"],"interiority_gate")
    if ig.get("evidence_already_carries_emotion") is True and ig.get("adds_new_causal_information") is False and ig.get("delete_or_keep")!="DELETE_REDUNDANT_EXPLANATION":
        e.append("redundant emotion naming should be deleted when evidence already carries it")

    sk=d.get("self_knowledge",{})
    req(e,sk,["level","author_model","character_available_words","forbidden_author_terms_in_character_voice","possible_future_level"],"self_knowledge")
    if sk.get("level") not in SELF_KNOWLEDGE or sk.get("possible_future_level") not in SELF_KNOWLEDGE: e.append("invalid self knowledge level")
    if sk.get("level") in {"K0","K1","K2"} and not sk.get("forbidden_author_terms_in_character_voice"):
        e.append("low self knowledge requires author-character vocabulary firewall")

    pd=d.get("punctuation_decisions",[])
    if not isinstance(pd,list) or len(pd)<2: e.append("punctuation decisions require at least two examples")
    for i,x in enumerate(pd):
        req(e,x,["line","literal_sentence_type","speech_act","expects_answer","rhetorical_pressure","breath_breaks","interruption_type","finality","chosen_punctuation","reason"],f"punctuation[{i}]")
        if x.get("chosen_punctuation") not in PUNCT: e.append(f"punctuation[{i}] invalid mark")
        if "哪回下雨" in x.get("line","") and x.get("speech_act","").find("反问")>=0 and x.get("chosen_punctuation")!="？":
            e.append("rhetorical question must preserve interrogative pressure")
    mr=d.get("medium_router",{})
    req(e,mr,["mode","novel_allows_indirect_interiority","screenplay_requires_playable_evidence","screenplay_forbids_unplayable_psychology_as_action"],"medium_router")
    if mr.get("mode") not in MEDIUM: e.append("invalid medium mode")
    if mr.get("screenplay_requires_playable_evidence") is not True or mr.get("screenplay_forbids_unplayable_psychology_as_action") is not True:
        e.append("screenplay must require playable evidence")
    if d.get("release_claim") in OVERCLAIMS: e.append("release claim exceeds static evidence")
    return e

def main():
    p=Path(sys.argv[1] if len(sys.argv)>1 else Path(__file__).resolve().parents[1]/"references"/"human-behavior-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())
