#!/usr/bin/env python3
from __future__ import annotations
import json,sys
from pathlib import Path
SCHEMA='JINGXU-STORYBOARD-PACKAGE-1.1'
ROLES={'ESTABLISH','MASTER','PRIMARY_ACTION','REACTION','INSERT','REORIENT','POV','CUTAWAY','TRANSITION','FINAL_HOLD'}
FUNCS={'ORIENT','PRESSURE','ACTION','REACTION','REVEAL','DECISION','PAYOFF','RESIDUE'}
DMODES={'SYNC','OS','VO','PHONE','RADIO','NONE'}
TRACKS={'CREATIVE_CUT','SAFETY_COVERAGE','BOTH'}
EXPANSIONS={'VISUAL_CLARIFICATION','SPATIAL_CLARIFICATION','BLOCKING_EXPANSION','PERFORMANCE_EVIDENCE','SOUND_REALIZATION','EDIT_INTERFACE','PRODUCTION_SOLUTION'}
FORBIDDEN_EXPANSIONS={'NEW_MEMORY','NEW_TRAUMA','NEW_MOTIVE','NEW_CLUE','NEW_DIALOGUE','NEW_RELATIONSHIP_FACT','NEW_CHARACTER_DECISION','NEW_OUTCOME','NEW_THEME_STATEMENT','NEW_TIME_OR_LOCATION_FACT'}
OVER={'HUMAN_REVIEWED','PRODUCTION_VALIDATED','CAMERA_REHEARSED','ANIMATIC_REVIEWED','FULLY_UNDERSTOOD_SHOT_ALGORITHM'}
BAD_COUNT_BASES={'WORD_COUNT','CHARACTER_COUNT','PAGE_COUNT','FIXED_SECONDS','ONE_BEAT_ONE_SHOT'}

def validate(d):
 e=[];w=[]
 def req(obj,keys,prefix,allow_false=False):
  for k in keys:
   if k not in obj or obj.get(k) is None or (not allow_false and obj.get(k) in ('',[],False)):
    e.append(f'{prefix} missing {k}')
 if d.get('schema_version')!=SCHEMA:e.append('wrong schema_version')
 if d.get('controller')!='jingxu':e.append('controller must be jingxu')
 if d.get('creates_new_story_truth') is not False:e.append('must not create new story truth')
 src=d.get('source_contract',{});req(src,['title','version','source_hash','source_format_profile','story_truth_locked','dialogue_lock','scene_ids','paired_evidence_level'],'source_contract')
 if src.get('story_truth_locked') is not True:e.append('story truth must be locked')
 metrics=d.get('source_metrics',{});req(metrics,['screenplay_character_count','dialogue_character_count','usage','shot_count_basis'],'source_metrics')
 if metrics.get('shot_count_basis') in BAD_COUNT_BASES:e.append('shot count cannot be derived from word/page/fixed-time ratio')
 if metrics.get('shot_count_basis')!='BEAT_STATE_OBSERVATION_COVERAGE':e.append('invalid shot count basis')
 if any(x in metrics.get('usage',[]) for x in ['SHOT_COUNT_GENERATION','CUT_FREQUENCY_GENERATION']):e.append('source metrics misuse for shot count')
 pro=d.get('project_profile',{});req(pro,['medium','aspect_ratio','target_edit_duration_s','delivery_profile','speech_rate_chars_per_second','timing_status'],'project_profile')
 rate=float(pro.get('speech_rate_chars_per_second',0) or 0)
 scenes=d.get('scenes',[])
 if not scenes:e.append('scenes must be nonempty');return e,w
 total_edit=0; all_ids=set(); declared=set(src.get('scene_ids',[]))
 for sc in scenes:
  sid=sc.get('scene_id')
  if sid not in declared:e.append(f'{sid}: scene not declared')
  req(sc,['source_beat_ids','allocated_edit_duration_s','coverage_strategy','beat_clusters','minimum_sufficient_test','shot_count_plan','pov_ownership','information_ledger','density_profile','energy_curve','production_expansion_ledger','creative_cut_plan','safety_coverage_plan','camera_setups','rollback_router','paired_learning'],f'scene {sid}')
  geo=sc.get('geography',{})
  if geo.get('defined') is not True:e.append(f'{sid}: geography not defined')
  req(geo,['interaction_axis','camera_side','screen_direction','reorientation_plan'],f'{sid} geography')
  alloc=float(sc.get('allocated_edit_duration_s',0) or 0); total_edit+=alloc
  clusters=sc.get('beat_clusters',[]); cluster_refs=set(); cluster_ids=set()
  for c in clusters:
   req(c,['cluster_id','source_refs','owner','local_goal','state_in','state_out','information_delta','relationship_delta','action_phase_range','spatial_continuity','temporal_continuity','pov_continuity','performance_continuity','decision'],f'{sid} cluster',allow_false=True)
   if c.get('cluster_id') in cluster_ids:e.append(f'{sid}: duplicate cluster id')
   cluster_ids.add(c.get('cluster_id'));cluster_refs.update(c.get('source_refs',[]))
   if c.get('decision')=='SPLIT' and not c.get('split_reasons'):e.append(f'{sid} {c.get("cluster_id")}: split lacks reasons')
   if c.get('decision','').startswith('MERGE') and not c.get('merge_reasons'):e.append(f'{sid} {c.get("cluster_id")}: merge lacks reasons')
  if not set(sc.get('source_beat_ids',[])).issubset(cluster_refs):e.append(f'{sid}: beat clustering incomplete')
  m=sc.get('minimum_sufficient_test',{});req(m,['source_clusters','independent_information_views','independent_reaction_views','required_reorientation_views','action_stage_views','pov_switches','mandatory_edit_interfaces','mergeable_views','proposed_n_min','proof_of_sufficiency'],f'{sid} minimum test',allow_false=True)
  counts=sc.get('shot_count_plan',{});req(counts,['necessary_shots_n_min','coverage_shots_n_coverage','creative_edit_shots_n_edit','camera_setups_n_setup','count_basis'],f'{sid} count plan')
  nmin=int(counts.get('necessary_shots_n_min',0) or 0);ncov=int(counts.get('coverage_shots_n_coverage',0) or 0);nedit=int(counts.get('creative_edit_shots_n_edit',0) or 0);nset=int(counts.get('camera_setups_n_setup',0) or 0)
  if not (0<nmin<=nedit<=ncov):e.append(f'{sid}: invalid N_MIN/N_EDIT/N_COVERAGE relation')
  if not (0<nset<=ncov):e.append(f'{sid}: invalid N_SETUP relation')
  if m.get('proposed_n_min')!=nmin:e.append(f'{sid}: minimum test and count plan disagree')
  if counts.get('count_basis')!='BEAT_STATE_OBSERVATION_COVERAGE':e.append(f'{sid}: count plan uses invalid basis')
  pov=sc.get('pov_ownership',{});req(pov,['default_mode','audience_follows','first_discoverer','delayed_discoverers','excluded_characters','permitted_objective_information','forbidden_early_information','pov_transfer_points','recovery_method'],f'{sid} pov',allow_false=True)
  if pov.get('default_mode') in {'CHARACTER_BOUND','RESTRICTED','UNRELIABLE'} and not pov.get('audience_follows'):e.append(f'{sid}: restricted POV lacks owner')
  density=sc.get('density_profile',{});req(density,['scene_type','dominant_need','cut_frequency_policy','preferred_observation_continuity','insert_policy','reaction_policy','hold_policy','prohibited_template'],f'{sid} density')
  energy=sc.get('energy_curve',{});req(energy,['entry_energy','pressure_curve','information_release_rate','physical_action_intensity','relationship_pressure','sound_density','camera_stability','cut_frequency','mandatory_holds','intentional_interruptions','exit_energy'],f'{sid} energy',allow_false=True)
  expansions={}
  for x in sc.get('production_expansion_ledger',[]):
   req(x,['expansion_id','source_refs','class','added_director_information','source_fact_preserved','creates_new_story_fact','changes_character_knowledge','changes_scene_result','necessary_for','removable_without_story_change'],f'{sid} expansion',allow_false=True)
   if x.get('class') in FORBIDDEN_EXPANSIONS or x.get('class') not in EXPANSIONS:e.append(f'{sid}: illegal production expansion class')
   if x.get('creates_new_story_fact') is not False or x.get('changes_character_knowledge') is not False or x.get('changes_scene_result') is not False:e.append(f'{sid}: production expansion changes story truth')
   expansions[x.get('expansion_id')]=x
  creative=sc.get('creative_cut_plan',{});req(creative,['ordered_shot_ids','scene_edit_duration_s','state_handoffs','sound_handoffs','intended_experience'],f'{sid} creative cut')
  safety=sc.get('safety_coverage_plan',{});req(safety,['required_shot_ids','failure_protected','minimum_extra_coverage','removable_coverage'],f'{sid} safety coverage')
  setups={}
  for st in sc.get('camera_setups',[]):
   req(st,['setup_id','serves_shots','axis_side','camera_position','lens_family','height','lighting_state','sound_constraints','action_reset','actor_reset','estimated_complexity','artistic_gain','can_merge_with_setup'],f'{sid} setup',allow_false=True)
   setups[st.get('setup_id')]=st
  if len(setups)!=nset:e.append(f'{sid}: N_SETUP does not match setup records')
  pair=sc.get('paired_learning',{});req(pair,['evidence_level','source_screenplay_available','storyboard_available','revision_history_available','animatic_available','sample_or_rehearsal_available','final_edit_available','claim_limit'],f'{sid} paired learning',allow_false=True)
  if pair.get('evidence_level') in {'E0','E1','E2'} and pair.get('claim_limit') not in {'STATIC_DECISION_CANDIDATE','FORMAT_AND_FAILURE_ANALYSIS_ONLY'}:e.append(f'{sid}: evidence claim exceeds paired learning level')
  shots=sc.get('shots',[]);shotmap={};reaction_ids=set();creative_refs=set();planned_sum=0.0
  for sh in shots:
   q=sh.get('shot_id')
   if not q:e.append(f'{sid}: missing shot id');continue
   if q in all_ids:e.append('duplicate shot id '+q)
   all_ids.add(q);shotmap[q]=sh
   req(sh,['source_refs','track','capture_duration_s','planned_edit_use_s','setup_id','edit_role','primary_function','dramatic_job','observation_reason','information_delta','entry_condition','exit_condition','blocking_and_action','expansion_refs','state_in','state_out','fallback'],q,allow_false=True)
   if sh.get('track') not in TRACKS:e.append(f'{q}: invalid track')
   cap=float(sh.get('capture_duration_s',0) or 0);use=float(sh.get('planned_edit_use_s',0) or 0)
   if cap<=0 or use<0 or use>cap:e.append(f'{q}: invalid capture/edit duration')
   if sh.get('track')=='SAFETY_COVERAGE' and use!=0:e.append(f'{q}: safety-only shot cannot be pre-counted in edit')
   if sh.get('track') in {'CREATIVE_CUT','BOTH'}:planned_sum+=use;creative_refs.update(sh.get('source_refs',[]))
   if sh.get('setup_id') not in setups:e.append(f'{q}: unknown setup id')
   for xr in sh.get('expansion_refs',[]):
    if xr not in expansions:e.append(f'{q}: unknown expansion ref {xr}')
   if sh.get('edit_role') not in ROLES:e.append(f'{q}: invalid edit role')
   if sh.get('primary_function') not in FUNCS:e.append(f'{q}: invalid primary function')
   fr=sh.get('framing',{});req(fr,['shot_size','angle','camera_height','composition_mechanisms'],q+' framing')
   if len(fr.get('composition_mechanisms',[]))>3:e.append(f'{q}: too many composition mechanisms')
   ca=sh.get('camera',{});req(ca,['movement','movement_motivation','stop_condition','fallback_static'],q+' camera')
   if ca.get('movement')!='STATIC' and not ca.get('movement_motivation'):e.append(f'{q}: moving shot lacks motivation')
   ax=sh.get('axis_and_screen_direction',{});req(ax,['axis_side','gaze_target','screen_direction','axis_crossing','axis_recovery'],q+' axis',allow_false=True)
   if ax.get('axis_crossing') is True and ax.get('axis_recovery') in ('',None,'NOT_REQUIRED'):e.append(f'{q}: axis crossing lacks recovery')
   pe=sh.get('performance_and_reaction',{});req(pe,['trigger','reaction_owner','reaction_evidence'],q+' performance')
   if pe.get('reaction_id'):reaction_ids.add(pe['reaction_id'])
   di=sh.get('dialogue',{})
   if di.get('mode') not in DMODES:e.append(f'{q}: invalid dialogue mode')
   if di.get('new_text') is True:e.append(f'{q}: new dialogue not allowed')
   if di.get('mode')!='NONE' and not di.get('source_line_ref'):e.append(f'{q}: dialogue missing source line')
   so=sh.get('sound',{});req(so,['bed','events','tail_handoff'],q+' sound',allow_false=True)
   for ev in so.get('events',[]):req(ev,['class','source','trigger','dramatic_job'],q+' sound event')
   tb=sh.get('timing_budget',{});nums=['dialogue_s','action_s','reaction_s','camera_s','reorientation_s','overlap_s','occupied_s','allocated_capture_s']
   if any(k not in tb for k in nums):e.append(f'{q}: timing budget incomplete')
   else:
    exp=float(tb['dialogue_s'])+float(tb['action_s'])+float(tb['reaction_s'])+float(tb['camera_s'])+float(tb['reorientation_s'])-float(tb['overlap_s'])
    if abs(exp-float(tb['occupied_s']))>.15:e.append(f'{q}: occupied timing mismatch')
    if abs(float(tb['allocated_capture_s'])-cap)>.05:e.append(f'{q}: capture timing differs')
    if float(tb['occupied_s'])>cap+.05:e.append(f'{q}: timing exceeds capture duration')
    text=di.get('text','')
    if text and rate>0 and float(tb['dialogue_s'])+.15<len(''.join(text.split()))/rate:e.append(f'{q}: dialogue time below profile')
   hd=sh.get('edit_handles',{});req(hd,['clean_head_s','overlap_in_s','preferred_cut_window','overlap_out_s','clean_tail_s','match_basis'],q+' handles',allow_false=True)
   if sh.get('edit_role')=='INSERT' and not sh.get('information_delta'):e.append(f'{q}: insert lacks information')
   if sh.get('edit_role')=='REACTION' and not pe.get('reaction_evidence'):e.append(f'{q}: reaction lacks evidence')
  if len(shots)!=ncov:e.append(f'{sid}: N_COVERAGE does not match shot records')
  creative_ids=creative.get('ordered_shot_ids',[])
  if len(creative_ids)!=nedit:e.append(f'{sid}: N_EDIT does not match creative cut')
  if any(x not in shotmap for x in creative_ids):e.append(f'{sid}: creative cut references unknown shot')
  if any(shotmap.get(x,{}).get('track')=='SAFETY_COVERAGE' for x in creative_ids):e.append(f'{sid}: safety-only shot appears in creative cut')
  if abs(planned_sum-alloc)>.05 or abs(float(creative.get('scene_edit_duration_s',0))-alloc)>.05:e.append(f'{sid}: creative edit duration mismatch')
  if not set(sc.get('source_beat_ids',[])).issubset(creative_refs):e.append(f'{sid}: creative cut does not cover source beats')
  if not set(sc.get('required_reactions',[])).issubset(reaction_ids):e.append(f'{sid}: required reactions not covered')
  safety_ids=set(safety.get('required_shot_ids',[]))
  if len(safety_ids)!=ncov or safety_ids!=set(shotmap):e.append(f'{sid}: safety coverage plan must enumerate capture shots')
  info={x.get('shot_id'):x for x in sc.get('information_ledger',[])}
  if set(info)!=set(shotmap):e.append(f'{sid}: information ledger must cover every shot')
  for q,x in info.items():
   req(x,['audience_before','audience_gains','audience_believes_after','possible_misread','characters_who_gain','characters_excluded','action_triggered','next_shot_obligation'],f'{sid} info {q}',allow_false=True)
  suff=sc.get('coverage_sufficiency',{})
  for k in ['key_action_readable','key_reaction_readable','geography_recoverable','dialogue_turns_supported','inserts_returnable','legal_cut_windows','state_handoffs_valid','sound_handoffs_valid','n_min_proven','creative_and_safety_tracks_separated','setup_count_valid','production_expansion_clean']:
   if suff.get(k) is not True:e.append(f'{sid}: coverage failed {k}')
 if abs(total_edit-float(pro.get('target_edit_duration_s',0) or 0))>.05:e.append('project edit duration mismatch')
 if d.get('release_claim') in OVER:e.append('release claim exceeds static evidence')
 return e,w

if __name__=='__main__':
 p=Path(sys.argv[1] if len(sys.argv)>1 else 'fixtures/storyboard-package-test-fixture.json');e,w=validate(json.loads(p.read_text(encoding='utf-8')));print(json.dumps({'status':'PASS' if not e else 'FAIL','errors':e,'warnings':w},ensure_ascii=False,indent=2));raise SystemExit(0 if not e else 1)
