#!/usr/bin/env python3
"""Compare the delivered immutable files with the declared SHA-256 manifest.

Only the top-level replay_outputs/ directory is mutable. A matching manifest
establishes byte consistency, not authorship, authenticity or theorem validity.
"""
from pathlib import Path, PurePosixPath
import hashlib, json, re

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

def unique_object(pairs):
    d={}
    for key,value in pairs:
        if key in d:
            raise ValueError('Duplicate manifest key: '+key)
        d[key]=value
    return d

def main():
    try:
        manifest=json.loads((ROOT/'SHA256.json').read_text(),object_pairs_hook=unique_object)
        if not isinstance(manifest,dict) or not manifest:
            raise ValueError('Empty or malformed manifest')
        for name,digest in manifest.items():
            p=PurePosixPath(name)
            if (p.is_absolute() or '..' in p.parts or str(p)!=name
                    or name=='SHA256.json' or p.parts[0]=='replay_outputs'):
                raise ValueError('Invalid immutable path: '+name)
            if not isinstance(digest,str) or not re.fullmatch('[0-9a-f]{64}',digest):
                raise ValueError('Invalid digest: '+name)
        files={}
        for p in ROOT.rglob('*'):
            rel=p.relative_to(ROOT)
            if rel.parts[0]=='replay_outputs':
                continue
            if p.is_symlink():
                raise ValueError('Symlink in immutable payload: '+str(rel))
            if p.is_file() and str(rel)!='SHA256.json':
                files[rel.as_posix()]=p
        if set(files)!=set(manifest):
            raise ValueError('Unlisted or missing payload: '+repr(sorted(set(files)^set(manifest))))
        for name,digest in manifest.items():
            if hashlib.sha256(files[name].read_bytes()).hexdigest()!=digest:
                raise ValueError('Hash mismatch: '+name)
    except (OSError,ValueError,KeyError) as exc:
        raise SystemExit(str(exc))
    print(f'Verified {len(manifest)} immutable payload hashes. No mathematical or authenticity claim follows from this check.')

if __name__=='__main__':
    main()
