from pathlib import Path
import re,json,hashlib,collections

root=Path(__file__).parent/'app'
base=root/'supabase/definitions'
schema=(root/'supabase/schema.sql').read_text(encoding='utf-8')
allfiles=sorted(base.rglob('*.sql'))
deep_names=set('''calculate_strength_observation_v2 calculate_max_rep_observation_v2 classify_set_purpose_v3 strength_estimation_load_percent_v1 strength_observations_project_v1 strength_session_reference_apply_v1 strength_daily_state_apply_v1 strength_votes_build_v1 refresh_user_strength_estimation_projection_from_v1 compute_stats_projection_job_v1 compute_stats_projection_job_engine_v1 run_stats_projection_step_v1 publish_stats_projection_job_v1 publish_stats_projection_job_engine_v1 stats_projection_stop_v1 claim_stats_projection_job_v1__text claim_user_exercise_stats_refresh_job_v1 stats_projection_revivable_jobs_v1 sync_user_stats_refresh_state_from_job get_user_stats_refresh_freshness enqueue_user_exercise_stats_refresh_job_core enqueue_user_exercise_stats_refresh_scope_v1 stats_projection_worker_kick_v1 get_data_modules_v1 data_module_family_home_v1 data_module_home_versions_v1 data_module_family_calendar_v1 save_session_v5 save_session_v5_engine refresh_session_numeric_contributions_v1 session_write_answer_v1 exercise_set_part_stats_v1 refresh_user_sequential_projections_v1 refresh_user_max_rep_projection_from_v1 refresh_user_set_observations_v1 exercise_set_part user_exercise_strength_states user_exercise_strength_observations user_exercise_set_observations user_exercise_max_rep_observations session_numeric_inputs_v1 training_effective_load canonical_duration_seconds_v1 canonical_distance_meters_v1 validate_session_payload_v5_core exercise_set_part_before_row_v1 stats_set_observation_inputs_v1 stats_metric_inputs_v1 exercise_set_part_before_row_core_v1 strength_set_metrics_map_json normalize_exercise_set_outcome_core_v1 set_score_session_v2 stats_sequential_score_parts_v1 set_score_recent_next_v1 refresh_user_metric_events_v1 stats_lock_v1 stats_projection_statement_budget_v1 stats_sequential_checkpoint_read_v1 validate_stats_projection_payload_v1 stats_projection_worker_settings stats_projection_tables_v1 guard_user_stats_refresh_projection_publication stats_scope_freshness_v1 refresh_user_strength_projection_bundle_from_v1 check_own_stats_core_v1'''.split())
deep_names.update('workout_mutation_commit_v1 get_session_mutation_receipt_v2 workout_set_score_preview_v1 save_session_state_v1 save_session_state_v1_engine'.split())
extra_names=set('''session_document_insert_v1 session_document_update_v1 delete_session_v5_engine delete_session_v5 save_session_state_v1 save_session_state_v1_engine build_session_record_v1 write_session_children_v5 workout_set_score_preview_v1 session_set_totals_v1 record_part_load_snapshot_v1 normalize_exercise_set_load_unit_core session_write_inbox_open_v1 session_write_inbox_interpreted_v1 session_write_answer_kind_v1 session_write_inbox attach_strength_metrics_map_to_json_v1 attach_strength_metrics_to_json_v1 calendar_strength_day_metrics_map_v1 calendar_strength_session_metrics_map_v1 get_log_table_cell_detail get_log_table_month get_log_table_month_v2_core get_calendar_day_summary get_home_year_activity get_user_home_benchmark_prs_json get_user_recent_prs_json'''.split())
files=[]
for p in allfiles:
    rel=p.relative_to(base)
    if rel.parts[0]=='stats' or p.stem.startswith('data_module_') or p.stem in deep_names|extra_names or (rel.parts[0]=='calendar' and rel.parts[1]=='tables'):
        files.append(p)
items=[]
for p in files:
    text=p.read_text(encoding='utf-8')
    lines=text.splitlines()
    body=re.split(r'\n(?:REVOKE|GRANT) ',text,1)[0]
    decl=next((x for x in lines if x.startswith('CREATE ')), '')
    calls=sorted(set(re.findall(r'(?i)\bpublic\."?([a-z_][a-z_0-9]*)"?\s*\(',body)))
    raises=[{'line':i,'text':s.strip()} for i,s in enumerate(lines,1) if re.search(r'\braise\s+(exception|warning)\b',s,re.I)]
    catches=[{'line':i,'text':s.strip()} for i,s in enumerate(lines,1) if re.search(r'\bexception\s+when\b',s,re.I)]
    checks=[{'line':i,'text':s.strip()} for i,s in enumerate(lines,1) if re.search(r'\bCONSTRAINT\b.*\bCHECK\b',s)]
    schema_line=next((i for i,s in enumerate(schema.splitlines(),1) if s==decl),None)
    category=('statistics_function' if '/stats/functions/' in p.as_posix() else 'statistics_table' if '/stats/tables/' in p.as_posix() else 'read_module' if p.stem.startswith('data_module_') or p.stem=='get_data_modules_v1' else 'write_read_dependency')
    items.append({'path':p.relative_to(root).as_posix(),'name':p.stem,'category':category,'lines':len(lines),'sha256':hashlib.sha256(text.encode()).hexdigest(),'schema_line':schema_line,'review_level':'manual_boundary_and_contract_review' if p.stem in deep_names else 'inventory_and_failure_boundary_scan','calls':calls,'raises':raises,'catches':catches,'checks':checks})
report={'basis':{'app_commit':'0a6e4cdd6207423f27e4d5de5333a2d4e593488a','docs_commit':'5cda2d33','date':'2026-10-03','method':'Canonical definitions + schema declaration mapping, static call/error/constraint inventory, selected full manual boundary review. No production access, no DB execution, no product edits.','scope':'All stats canonical functions and tables; all data_module canonical functions plus shell get_data_modules; calendar projection tables and listed direct workout/read dependencies. Historical migrations excluded from current-code inventory.','limits':'Regex call scan is not a SQL parser; dynamic SQL and trigger execution require manual boundary review; full arithmetic correctness, production data incidence, query timing, migration replay and fault injection are unverified.'},'counts':dict(collections.Counter(i['category'] for i in items)),'review_counts':dict(collections.Counter(i['review_level'] for i in items)),'items':items}
(Path(__file__).parent/'server-inventory.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps({'counts':report['counts'],'review_counts':report['review_counts'],'total':len(items),'missing_schema_declaration':[x['path'] for x in items if not x['schema_line']]},ensure_ascii=False))
