#!/usr/bin/env python3
from __future__ import annotations
import json,sys
from pathlib import Path
ALLOWED_DISTANCE={"D0_DIRECT","D1_ELLIPTIC","D2_HINT","D3_DEFLECT","D4_IRONIC_CODED","D5_OPPOSITE_SURFACE"}
OVERCLAIMS={"HUMAN_REVIEWED","DIALOGUE_TABLE_READ","PERFORMANCE_VALIDATED","PRODUCTION_VALIDATED","CROSS_MODEL_BEST"}
ALLOWED_INTERRUPT_SOURCES={"PREEXISTING_SCENE_FACT","CONTINUOUS_PRESSURE","MICRO_AFFORDANCE"}
ALLOWED_RESUME={"RESUME","REPHRASE","ABANDON","DELAY","ESCALATE"}

def validate(d):
    e=[]
    if d.get('schema')!='JINGHUA-DIALOGUE-LIFE-3.0': e.append('schema must be JINGHUA-DIALOGUE-LIFE-3.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('dialogue runtime must not create a new IR')
    pol=d.get('runtime_policy',{})
    expected={
      'social_redundancy_policy':'FUNCTIONAL_NOT_QUOTA',
      'subtext_policy':'CONDITIONAL_NOT_MANDATORY',
      'imperfection_policy':'MOTIVATED_NOT_RANDOM',
      'dialect_policy':'PRAGMATICS_BEFORE_ORTHOGRAPHY',
      'extreme_speech_policy':'STABLE_PRIVATE_LOGIC_NOT_RANDOM_NOISE',
      'somatic_policy':'CONTEXTUAL_NOT_QUOTA',
      'fatigue_policy':'MULTIDIMENSIONAL_NOT_SINGLE_THRESHOLD',
      'attention_policy':'SALIENT_AND_STATEFUL_NOT_RANDOM',
      'taboo_policy':'PRESSURE_NOT_PRESET_BREAKDOWN',
      'conversation_memory_policy':'STATEFUL_NOT_TURN_RESET',
      'humanization_policy':'EVIDENCE_TRIGGERED_NOT_DECORATIVE',
      'interruption_authority':'NO_NEW_STORY_EVENT',
      'context_budget_policy':'MINIMUM_SUFFICIENT_NOT_FULL_DUMP'
    }
    for k,v in expected.items():
        if pol.get(k)!=v: e.append(f'{k} must be {v}')
    scene=d.get('scene',{})
    if scene.get('scene_locked') is not True: e.append('scene must be locked before dialogue runtime')
    mods=scene.get('modifiers',[])
    if 'BASE_NATURAL' not in mods: e.append('BASE_NATURAL modifier required')
    ctx=d.get('life_context',{})
    for k in ['common_ground_present','belief_state_present','desire_depth_present','listener_model_present','facework_present']:
        if ctx.get(k) is not True: e.append('life context missing: '+k)
    if ctx.get('semantic_distance') not in ALLOWED_DISTANCE: e.append('invalid semantic distance')
    rz=d.get('realization',{})
    if rz.get('random_stutter') is True: e.append('random stutter is not valid humanization')
    if rz.get('all_speakers_share_fillers') is True: e.append('all speakers may not share filler profile')
    if rz.get('all_lines_must_advance_plot') is True: e.append('all lines may not be forced to advance plot')
    if rz.get('mandatory_noncooperative_turn') is True: e.append('noncooperative turn may not be mandatory decoration')
    if rz.get('mandatory_humanization_event') is True: e.append('humanization event may not be mandatory decoration')
    if rz.get('social_redundancy_function') in (None,'NONE') and scene.get('modifiers') and 'BASE_NATURAL' in mods and rz.get('has_nonplot_redundancy',False):
        e.append('nonplot redundancy requires interpersonal or rhythm function')
    if 'STRATEGIC' in mods:
        s=d.get('strategic_public_line',{})
        for k in ['public_meaning','private_signal','real_target','recordable_meaning','plausible_denial','induced_next_move']:
            if not s.get(k): e.append('strategic public line missing: '+k)
    if scene.get('speaker_count',0)>=3 and 'GROUP' in mods:
        g=d.get('group_conversation_graph',{})
        if not g.get('topic_controller'): e.append('group scene requires topic controller')
        if 'who_can_interrupt_whom' not in g: e.append('group scene requires interruption rights')
    ed=d.get('emotion_deformation',{})
    if ed.get('enabled') and ed.get('random_incoherence') is True: e.append('emotion deformation cannot be random incoherence')
    pr=d.get('private_reality',{})
    if pr.get('enabled'):
        if not pr.get('fixed_obsession'): e.append('private reality requires fixed obsession')
        if pr.get('random_noise') is True: e.append('private reality cannot be random noise')
    if 'EMBODIED' in mods:
        x=d.get('embodied_interruption',{})
        if x.get('enabled') is not True: e.append('EMBODIED modifier requires embodied interruption state')
        if x.get('source') not in ALLOWED_INTERRUPT_SOURCES: e.append('embodied interruption source must stay within locked scene')
        if not x.get('state_owner'): e.append('embodied interruption missing: state_owner')
        for k in ['body_load','environmental_event','speech_point_interrupted','speaker_read_of_event','emotional_delta']:
            if not x.get(k): e.append('embodied interruption missing: '+k)
        if x.get('resume_policy') not in ALLOWED_RESUME: e.append('invalid embodied resume policy')
        if x.get('creates_new_story_fact') is not False: e.append('dialogue interruption may not create new story fact')
        if x.get('fixed_length_reduction_ratio') not in (None,False): e.append('fixed utterance length reduction ratio is forbidden')
    if 'FATIGUED' in mods:
        f=d.get('fatigue',{})
        if not f.get('state_owner'): e.append('fatigue state missing: state_owner')
        for k in ['physical_capacity','cognitive_bandwidth','emotional_tolerance','social_patience','personal_degradation_style','state_delta_after_turn']:
            if not f.get(k): e.append('fatigue state missing: '+k)
        if f.get('uses_single_numeric_threshold') is not False: e.append('fatigue may not use single numeric threshold')
    if 'ATTENTION_LAG' in mods:
        a=d.get('attention',{})
        if not a.get('state_owner'): e.append('attention lag missing: state_owner')
        for k in ['current_focus','salient_trigger','unresolved_phrase','delayed_response_target','reason_for_lag','reentry_condition']:
            if not a.get(k): e.append('attention lag missing: '+k)
        if a.get('random_topic_jump') is True: e.append('attention lag cannot be random topic jump')
    if 'TABOO' in mods:
        t=d.get('taboo',{})
        if not t.get('state_owner'): e.append('taboo graph missing: state_owner')
        for k in ['node','substitutions','public_private_difference','first_defense','escalation_condition']:
            if not t.get(k): e.append('taboo graph missing: '+k)
        if t.get('forced_breakdown') is True: e.append('taboo pressure may not force predetermined breakdown')
    if 'STATEFUL' in mods:
        c=d.get('conversation_state_memory',{})
        if c.get('enabled') is not True: e.append('STATEFUL modifier requires conversation state memory')
        for k in ['unanswered_questions','unfinished_utterances','offense_debts','repair_attempts','failed_repairs','topic_ghosts','silence_debts','promises_or_commitments']:
            if k not in c: e.append('conversation state memory missing: '+k)
        if not c.get('state_carryover_to_next_turn'): e.append('conversation state memory missing: state_carryover_to_next_turn')
    lf=d.get('listener_feedback',{})
    if lf.get('enabled'):
        if not lf.get('state_owner'): e.append('listener feedback missing: state_owner')
        for k in ['feedback_event','speaker_interpretation','speaker_adaptation','relation_or_face_effect']:
            if not lf.get(k): e.append('listener feedback missing: '+k)
        if lf.get('creates_story_truth') is not False: e.append('listener feedback may not create story truth')
    deep={'EMBODIED','FATIGUED','ATTENTION_LAG','TABOO','STATEFUL'} & set(mods)
    if deep:
        r=d.get('invocation_receipt_extension_v3',{})
        if str(r.get('runtime_version'))!='3.0': e.append('v3 receipt missing runtime_version')
        active=set(r.get('active_v3_modifiers',[]))
        if not deep.issubset(active): e.append('v3 receipt missing active modifiers')
        for k in ['minimum_sufficient_context_pass','no_new_story_fact_pass','state_carryover_pass','anti_decoration_gate_pass']:
            if r.get(k) is not True: e.append('v3 receipt incomplete: '+k)
    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 'references/dialogue-pragmatics-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())
