#!/usr/bin/env python3
"""Check public-file hashes, rerun both implementations and compare exact witnesses."""
import hashlib
import json
from pathlib import Path
import subprocess
import sys

ROOT = Path(__file__).resolve().parent

def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()

def verify_files(root):
    manifest=json.loads((root/'manifest.json').read_text())
    if manifest.get('schema')!=1 or not manifest.get('files'):raise ValueError('Invalid file manifest')
    for name,expected in manifest['files'].items():
        path=root/name
        if not path.is_file() or path.is_symlink() or not path.resolve().is_relative_to(root.resolve()) or len(expected)!=64:
            raise ValueError('Invalid packet file')
        if digest(path)!=expected:raise ValueError('Hash mismatch: '+name)
    return manifest

def execute(args):
    result=subprocess.run(args,cwd=ROOT,capture_output=True,timeout=5,check=True,env=__import__('os').environ|{'PYTHONDONTWRITEBYTECODE':'1'})
    return result.stdout

def main():
    verify_files(ROOT)
    primary=execute([sys.executable,'check.py','input.json'])
    if primary!=(ROOT/'expected-primary.json').read_bytes():raise ValueError('Primary output differs from recorded output')
    execute([sys.executable,'test_primary.py'])
    independent=execute(['node','independent/check-prefix.mjs'])
    if independent!=(ROOT/'independent/result.json').read_bytes():raise ValueError('Second output differs; check pinned runtime and source')
    a=json.loads(primary);b=json.loads(independent)
    projected=[{'start':r['start'],'trajectory':r['orbit'],'prefix':[int(x) for x in r['parity_prefix']],'tau':r['first_hit']} for r in a['records']]
    other=[{k:r[k] for k in ('start','trajectory','prefix','tau')} for r in b['certificates']]
    if projected!=other or a['disposition']!='counterexample' or b['verification']['tests_passed']!=31:
        raise ValueError('Implementations disagree or tests incomplete')
    if digest(ROOT/'independent/check-prefix.mjs')!=b['verification']['source_sha256']:
        raise ValueError('Second implementation source identity changed')
    report={'schema':1,'comparison':'exact agreement on both full trajectories, before-step prefixes and minimal first-hit times',
            'disposition':'finite counterexample to four-bit prefix sufficiency','primary_tests':8,'separate_implementation_tests':31,
            'python':sys.version.split()[0],'node':execute(['node','--version']).decode().strip(),
            'primary_source_sha256':digest(ROOT/'check.py'),'primary_input_sha256':digest(ROOT/'input.json'),
            'primary_output_sha256':hashlib.sha256(primary).hexdigest(),
            'separate_source_sha256':digest(ROOT/'independent/check-prefix.mjs'),'separate_output_sha256':hashlib.sha256(independent).hexdigest(),
            'limits':'Two separately constructed programs within AI-assisted work; not external, human or formal verification. No novelty or Collatz-conjecture conclusion.'}
    print(json.dumps(report,indent=2,sort_keys=True))

if __name__=='__main__':
    try:main()
    except (ValueError,OSError,subprocess.SubprocessError) as error:
        print('Reproduction failed: '+str(error),file=sys.stderr);raise SystemExit(1)
