#!/usr/bin/env python3
"""Offline source/pure oracle/privacy/seal conservation check, no runtime/SQL."""
import hashlib
import importlib.util
import json
import stat
import subprocess
from pathlib import Path
R=Path(__file__).resolve().parent
BASE=R.parent
checks=0


def ok(t):
    global checks
    assert t
    checks+=1


if __name__=='__main__':
    a=json.loads((R/'source-audit.json').read_bytes())
    WS=Path(a['workspace'])
    for name,h in a['source_sha256'].items():ok(hashlib.sha256((WS/'zhctproject/store'/name).read_bytes()).hexdigest()==h)
    for name,h in a['excluded_AI_same_name'].items():ok(hashlib.sha256((WS/'zhctproject/ai_api'/name).read_bytes()).hexdigest()==h)
    ok(a['searched_store_application_php_files']==957)
    ok(len(a['reviewed_target_alias_files'])==13 and len(a['target_model_calls'])==57)
    ok(len(a['target_model_potential_mutations'])==11 and a['raw_Db_name_actual_mutations']==[])
    ok(len(a['raw_Db_name_exact_target_calls'])==14 and sum(not x['line_comment'] for x in a['raw_Db_name_exact_target_calls'])==12)
    generated=json.loads(subprocess.check_output(['python3',str(R/'build-pure-cases.py')]))
    fixture=json.loads((R/'private-evidence/pure-cases.json').read_bytes());ok(fixture==generated)
    results=json.loads((R/'private-evidence/pure-runtime-results.json').read_bytes())
    for lane,version in [('B','7.3.33'),('C','7.3.32')]:
        r=results[lane]['result'];ok(r['PHP_VERSION']==version and r['status']=='PURE_GREEN_NOT_DB_OR_API_FIX')
        ok(r['checks']==778 and r['failures']==[])
        ok(r['original_cases']==43 and r['model_only_cases']==16 and len(r['rows'])==59)
        ok(len(r['negative_precondition_rejections'])==9 and r['SQL']==r['HTTP']==0)
        for c,observed in zip(fixture['cases'],r['rows']):
            ok(c['case_id']==observed['case_id'] and c['original_input']==observed['original_input'] and c['provenance']==observed['provenance'])
            ok(observed['parsed_double']['native_double_hex']==c['expected_parse64_hex'])
            ok(observed['stored_float32_as_double']['native_double_hex']==c['expected_stored_double_hex'])
            ok(observed['direct_getter']['native_double_hex']==c['expected_direct_getter_hex'])
            for key,h in c['source_model_stage_hex'].items():ok(observed[key]['native_double_hex']==h)
            ok(observed['was_clipped']==c['expected_was_clipped'])
    ok(results['B']['result']['rows']==results['C']['result']['rows'])
    mutations=json.loads((R/'private-evidence/pure-mutations.json').read_bytes());ok(len(mutations['rejected'])==8)
    transport=json.loads((R/'private-evidence/transport-pure-results.json').read_bytes());ok(transport['precision']==14 and transport['PDO_bind_calls']==transport['SQL']==0)
    ok(len(transport['rows'])==3)
    for row in transport['rows']:ok(row['source_string_model_stored_hex']!=row['N_mimic_model_stored_hex'])
    ok(stat.S_IMODE((R/'private-evidence').stat().st_mode)==0o700)
    private_files=[p for p in (R/'private-evidence').iterdir() if p.is_file()]
    for p in private_files:ok(stat.S_IMODE(p.stat().st_mode)==0o600)
    sealed=[]
    for folder,name,key in [(BASE,'execution-seal.json','public_sha256'),(BASE/'primary-source-derivation-20261011','research-manifest.json','files'),(BASE/'half-tie-execution-20261011','seal.json','public_sha256'),(BASE/'c-literal-rint-proposal-20261011','review-seal.json','public_sha256'),(BASE/'c-literal-rint-execution-20261011','seal.json','public_sha256')]:
        m=json.loads((folder/name).read_bytes())
        for rel,h in m[key].items():ok(hashlib.sha256((folder/rel).read_bytes()).hexdigest()==h)
        sealed.append({'seal':str((folder/name).relative_to(BASE)),'unchanged_files':len(m[key])})
    print(json.dumps({'status':'PURE_AUDIT_HANDOFF_VERIFIED_NOT_TRANSPORT_OR_BUSINESS_ACCEPTANCE','assertions':checks,'private_files_0700_0600':len(private_files),'previous_seals_unchanged':sealed,'SQL':0,'HTTP':0,'main_source_changes':0},indent=2))
