#!/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"}
ALLOWED_VALENCE={"pleasant","mixed","unpleasant","neutral_or_unclear"}
ALLOWED_AROUSAL={"low","medium","high","unstable"}
ALLOWED_DOMINANCE={"powerless","balanced","controlling"}
ALLOWED_CERTAINTY={"uncertain","split","certain"}
ALLOWED_ATTACHMENT={"approach","hold_distance","withdraw","ambivalent"}
ALLOWED_EXPOSURE={"safe","watched","exposed","humiliated"}
ALLOWED_ACTION={"approach","avoid","attack","freeze","repair","control","submit","observe"}
ALLOWED_MASKING={"open","moderated","strongly_masked","false_display"}
ALLOWED_GRANULARITY={"low","medium","high"}
ALLOWED_AWARENESS={"low","uneven","high"}
ALLOWED_DISPLAY_SOURCE={"personal","relational","professional","institutional","cultural","none"}
ALLOWED_REGULATION={"none","reappraise","suppress","dampen","amplify","mask","substitute","humor","proceduralize"}
ALLOWED_MEDIUM={"NOVEL","SCREENPLAY"}

EXPECTED_POLICIES={
  "emotion_model_policy":"DIMENSION_PLUS_LABEL_NOT_LABEL_ONLY",
  "emotion_mix_policy":"MIXED_AND_META_ALLOWED_NOT_MANDATORY",
  "display_policy":"EXPRESSION_MAY_DIFFER_FROM_EXPERIENCE",
  "voice_policy":"CAUSAL_ACOUSTIC_REALIZATION_NOT_EMOTION_TAG_LOOKUP",
  "tag_policy":"NECESSARY_NOT_DECORATIVE",
  "repetition_policy":"AUTHOR_REPETITION_NOT_CHARACTER_SIGNATURE",
  "medium_policy":"NOVEL_AND_SCREENPLAY_DIFFERENT",
  "culture_policy":"CONTEXTUAL_DISPLAY_RULE_NOT_STEREOTYPE",
  "granularity_policy":"CHARACTER_SPECIFIC_LABEL_ACCESS",
  "co_regulation_policy":"BIDIRECTIONAL_NOT_ONE_WAY",
  "affect_memory_policy":"STATEFUL_NOT_TURN_RESET",
}

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

def validate(d):
    e=[]
    if d.get("schema")!="JINGHUA-AFFECTIVE-VOICE-1.0": e.append("schema must be JINGHUA-AFFECTIVE-VOICE-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("affective runtime must not create a new IR")
    if d.get("stage")!="W6-W7": e.append("affective runtime must stay in W6-W7")
    if d.get("parent_runtime")!="DIALOGUE_SUBTEXT_AUX": e.append("affective runtime must remain inside DIALOGUE_SUBTEXT_AUX")
    if d.get("scene_lock") is not True: e.append("scene must be locked before affective realization")
    pol=d.get("runtime_policy",{})
    for k,v in EXPECTED_POLICIES.items():
        if pol.get(k)!=v: e.append(f"{k} must be {v}")

    a=d.get("affect_state_vector",{})
    req(e,a,["valence","arousal","dominance","certainty","attachment","social_exposure","action_tendency","masking"],"affect_state_vector")
    if a.get("valence") not in ALLOWED_VALENCE: e.append("invalid affect valence")
    if a.get("arousal") not in ALLOWED_AROUSAL: e.append("invalid affect arousal")
    if a.get("dominance") not in ALLOWED_DOMINANCE: e.append("invalid affect dominance")
    if a.get("certainty") not in ALLOWED_CERTAINTY: e.append("invalid affect certainty")
    if a.get("attachment") not in ALLOWED_ATTACHMENT: e.append("invalid affect attachment")
    if a.get("social_exposure") not in ALLOWED_EXPOSURE: e.append("invalid social exposure")
    if a.get("action_tendency") not in ALLOWED_ACTION: e.append("invalid action tendency")
    if a.get("masking") not in ALLOWED_MASKING: e.append("invalid masking")

    ap=d.get("appraisal",{})
    req(e,ap,["goal_relevance","goal_congruence","agency_attribution","controllability","certainty","norm_or_identity_relevance","relationship_meaning","loss_or_gain_forecast"],"appraisal")

    bl=d.get("emotion_blend",{})
    req(e,bl,["primary","strongest_unsolved_conflict"],"emotion_blend")
    if bl.get("primary") in ("COMPLEX","MIXED","HUMAN"):
        e.append("primary emotion may not be a generic complexity label")

    rd=d.get("regulation_display",{})
    req(e,rd,["experienced_affect","desired_self_state","desired_listener_state","public_private_context","display_rule_source","regulation_strategy","expressed_affect","leakage_channel","regulation_cost"],"regulation_display")
    if rd.get("display_rule_source") not in ALLOWED_DISPLAY_SOURCE: e.append("invalid display rule source")
    if rd.get("regulation_strategy") not in ALLOWED_REGULATION: e.append("invalid regulation strategy")
    if rd.get("display_rule_source")=="cultural" and not rd.get("public_private_context"):
        e.append("cultural display rule requires concrete context")

    lx=d.get("lexical_access",{})
    req(e,lx,["granularity","self_awareness","preferred_self_labels","generic_fallback_words","author_knows_but_character_would_not_say","bodily_or_behavioral_substitutions"],"lexical_access")
    if lx.get("granularity") not in ALLOWED_GRANULARITY: e.append("invalid emotion granularity")
    if lx.get("self_awareness") not in ALLOWED_AWARENESS: e.append("invalid self awareness")
    if lx.get("granularity")=="low" and len(lx.get("author_knows_but_character_would_not_say",[]))==0:
        e.append("low granularity requires author-character vocabulary separation")

    tr=d.get("trajectory",{})
    req(e,tr,["trigger","onset_style","current_phase","unresolved_residue","suppression_rebound","next_trigger_sensitivity","carryover_to_next_turn"],"trajectory")
    if str(tr.get("carryover_to_next_turn","")).upper() in {"NONE","RESET","NEUTRAL"}:
        e.append("affect trajectory may not auto-reset every turn")

    co=d.get("co_regulation",{})
    if co.get("enabled"):
        req(e,co,["regulator","target","regulator_goal","tactic","target_interpretation","target_affect_delta","relationship_delta","backfire_possible"],"co_regulation")
        if co.get("regulator")==co.get("target"): e.append("social co-regulation requires distinct agents")

    vr=d.get("voice_realization",{})
    req(e,vr,["body_precondition","breath_support","volume","pitch_tendency","pitch_variability","speech_rate","pause_pattern","stress_pattern","voice_quality","articulation","sentence_shape_effect","surface_tag_candidates"],"voice_realization")
    if vr.get("fixed_emotion_to_voice_lookup") is not False: e.append("voice realization may not use fixed emotion-to-voice lookup")

    vc=d.get("voice_contradiction",{})
    if vc.get("enabled"):
        req(e,vc,["experienced","expressed","reason","evidence","used_as_generic_style_trick"],"voice_contradiction")
        if vc.get("used_as_generic_style_trick") is True: e.append("voice contradiction may not be a generic style trick")

    tg=d.get("voice_tag_gate",{})
    req(e,tg,["dialogue_already_carries_state","action_already_carries_state","context_already_carries_state","voice_changes_meaning_or_power","omission_would_create_wrong_performance","tag_required","reason"],"voice_tag_gate")
    if tg.get("tag_required") is True and not (tg.get("voice_changes_meaning_or_power") or tg.get("omission_would_create_wrong_performance")):
        e.append("voice tag requires new performance information")
    if tg.get("tag_required") is False and not tg.get("reason"):
        e.append("voice tag rejection requires reason")

    rp=d.get("repetition_ledger",{})
    req(e,rp,["recent_tags","repeated_family","authorial_repetition_risk","character_signature","state_change_exception","action"],"repetition_ledger")
    if rp.get("action")=="ROTATE_SYNONYMS_ONLY": e.append("repetition may not be solved by synonym rotation")

    mr=d.get("medium_router",{})
    req(e,mr,["mode","novel_tag_density","screenplay_emotion_parenthetical_policy","psychology_explanation_in_dialogue"],"medium_router")
    if mr.get("mode") not in ALLOWED_MEDIUM: e.append("invalid medium mode")
    if mr.get("mode")=="SCREENPLAY" and mr.get("psychology_explanation_in_dialogue") is True:
        e.append("screenplay may not replace playable evidence with psychology explanation")

    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"/"affective-voice-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())
