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

OVERCLAIMS={'COMPARATIVE_BLIND_TESTED','HUMAN_REVIEWED','PRODUCTION_VALIDATED'}

def validate(d):
    e=[]
    if d.get('controller')!='juben': e.append('controller must remain juben')
    if d.get('story_truth_owner')!='Creative': e.append('Creative must retain story truth')
    if d.get('creates_new_ir') is not False: e.append('JINGHUA must not create a new IR')

    r=d.get('relational_morality',{})
    relation_keys=['toward_beloved','toward_strangers','toward_enemies']
    if sum(bool(r.get(k)) for k in relation_keys)<3: e.append('relational morality needs at least three relation classes')
    if not r.get('activation_conditions'): e.append('moral variation requires activation conditions')

    h=d.get('selective_humanity',{})
    if not h.get('actual_loss_accepted') or not h.get('plan_changed'):
        e.append('selective humanity must change plan and accept cost')
    if h.get('does_not_erase_harm') is not True: e.append('selective humanity may not erase harm')

    c=d.get('contradiction',{})
    for k in ['declared_value','dependent_interest','pressure_event','irreversible_choice','residue']:
        if not c.get(k): e.append('contradiction missing '+k)

    rv=d.get('revelation',{})
    if not rv.get('past_event_reinterpreted'): e.append('revelation must reinterpret past')
    if not rv.get('future_action_forced'): e.append('revelation must force future action')
    if rv.get('fair_clues') is not True: e.append('revelation requires fair clues')

    ts=d.get('trauma_strategy',{})
    for k in ['originating_event','learned_false_rule','survival_strategy','current_damage']:
        if not ts.get(k): e.append('trauma-strategy chain missing '+k)

    end=d.get('ending',{})
    for k in ['result','cost','residual_conflict','resonance_source']:
        if not end.get(k): e.append('ending missing '+k)
    if end.get('choice_irreversible') is not True: e.append('major ending choice must be irreversible')
    if end.get('causal_debt_accounted') is not True: e.append('ending must account causal debt')

    sp=d.get('scale_permission',{})
    for k in ['current_scale','evidence_level','permission','new_ally_needed','cost_of_permission']:
        if not sp.get(k): e.append('scale-permission missing '+k)

    th=d.get('three_horizon',{})
    for k in ['now','next','later']:
        if not th.get(k): e.append('three horizon missing '+k)
    oh=d.get('opponent_horizon',{})
    for k in ['current_action','prediction','use_of_success','fallback']:
        if not oh.get(k): e.append('opponent horizon missing '+k)

    ib=d.get('intensity_budget',{})
    peaks=ib.get('primary_peaks',[])
    if not isinstance(peaks,list) or len(peaks)>2: e.append('uncontrolled intensity peaks exceed two')
    if not ib.get('deliberately_lowered_axes'): e.append('intensity budget must lower other axes')

    t=d.get('theme',{})
    if t.get('proved_by_choices') is not True: e.append('theme must be proved by choices')
    if t.get('requires_summary_line') is True: e.append('theme may not depend on summary line')

    a=d.get('aftermath',{})
    for k in ['body_state','prop_state','relationship_state','public_record']:
        if not a.get(k): e.append('aftermath missing '+k)
    if a.get('persists_next_scene') is not True: e.append('aftermath must persist')

    g=d.get('genre_tone',{})
    if g.get('tone_preserved') is not True: e.append('genre tone must be preserved')
    if g.get('all_genres_forced_dark') is True: e.append('all genres may not be forced dark')

    n=d.get('network_consequence',{})
    if int(n.get('secondary_actors_reactivated',0))<2: e.append('major choice must reactivate at least two other actors')
    if n.get('institutional_response') is not True: e.append('system-scale choice requires institutional response')

    if d.get('release_claim') in OVERCLAIMS: e.append('release claim exceeds evidence')
    return e

def main():
    p=Path(sys.argv[1] if len(sys.argv)>1 else 'references/jinghua-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())
