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

def sha(p:Path)->str: return hashlib.sha256(p.read_bytes()).hexdigest()

def read_manifest(p:Path):
    out=[]
    for line in p.read_text(encoding='utf-8',errors='ignore').splitlines():
        if '  ' in line:
            h,n=line.split('  ',1); out.append((h,n))
    return out

def validate(root:Path):
    errors=[]; warnings=[]
    required=[
      'references/core-capability-preservation-manifest.md',
      'references/core-task-dispatch-runtime.md',
      'references/screenplay-reasoning-first-gate.md',
      'references/screenplay-causal-integrity-runtime.md',
      'references/script-doctor-root-cause-runtime.md',
      'references/medium-firewall-screenplay-novel.md',
      'references/jingxu-compat-storyboard-runtime.md',
      'references/end-to-end-core-promotion-gate.md',
      'references/upgrade-nonregression-gate.md',
      'references/core-golden-hashes-v1.4.json',
      'references/core-behavior-benchmark-fixture.json',
      'sources/jingxu-v1.2-compat/JINGXU_v1.2_EXPANDED_REFERENCE.md',
    ]
    for rel in required:
        if not (root/rel).is_file(): errors.append('missing required core asset: '+rel)
    skill=(root/'SKILL.md').read_text(encoding='utf-8',errors='replace')
    orch=(root/'references'/'screenwriting-production-orchestrator.md').read_text(encoding='utf-8',errors='replace')
    joined=skill+'\n'+orch
    for token in ['CORE_TASK_DISPATCH_RUNTIME','SCREENPLAY_CAUSAL_INTEGRITY_RUNTIME','SCRIPT_DOCTOR_ROOT_CAUSE_RUNTIME','MEDIUM_FIREWALL_SCREENPLAY_NOVEL','JINGXU_COMPAT_STORYBOARD_RUNTIME','end-to-end-core-promotion-gate.md','UPGRADE_NONREGRESSION_GATE']:
        if token not in joined: errors.append('missing core routing token: '+token)
    # Historical asset presence by path or exact content hash. Renames are allowed only if bytes are identical.
    curfiles=[p for p in root.rglob('*') if p.is_file() and '__pycache__' not in p.parts]
    byhash={}
    for p in curfiles: byhash.setdefault(sha(p),[]).append(p)
    for mf in ['SHA256SUMS-JINGHUA-v1.2-KB-FORMAT.txt','SHA256SUMS-JINGHUA-v1.4-THREE-AUTHORITY.txt']:
        mp=root/mf
        if not mp.exists(): errors.append('missing historical manifest: '+mf); continue
        for h,rel in read_manifest(mp):
            if '__pycache__/' in rel or rel.endswith('.pyc'):
                continue
            p=root/rel
            if p.exists():
                continue
            if h not in byhash:
                errors.append(f'historical asset lost: {mf}:{rel}')
    # Byte-exact protected core.
    gp=root/'references'/'core-golden-hashes-v1.4.json'
    if gp.exists():
        gold=json.loads(gp.read_text(encoding='utf-8'))
        for rel,expected in gold.get('protected_files',{}).items():
            p=root/rel
            if not p.exists(): errors.append('protected core missing: '+rel)
            elif sha(p)!=expected: errors.append('protected v1.4 core changed: '+rel)
    return errors,warnings

if __name__=='__main__':
    root=Path(sys.argv[1] if len(sys.argv)>1 else '.').resolve()
    e,w=validate(root)
    print(json.dumps({'status':'PASS' if not e else 'FAIL','errors':e,'warnings':w},ensure_ascii=False,indent=2))
    raise SystemExit(1 if e else 0)
