"""Build one reviewable patch against the frozen analysis source tree."""
from pathlib import Path
import difflib
import hashlib
import json
import subprocess

ROOT = Path(__file__).resolve().parent
BASE = Path('/Users/yixiay/Documents/codexWorkSpace/issues/output/597084-review/impact-2026-11-04/source')
EXPECTED = '0baa9ebe8b7f9ecc46f675acbf1f56ac65378957'

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

def main():
    head = subprocess.check_output(['git', '-C', str(BASE), 'rev-parse', 'HEAD'], text=True).strip()
    if head != EXPECTED:
        raise SystemExit('Baseline SHA changed; refusing to build a misleading patch.')
    if subprocess.check_output(['git', '-C', str(BASE), 'status', '--porcelain'], text=True).strip():
        raise SystemExit('Baseline worktree is not clean.')
    files = sorted(p for p in (ROOT/'code').rglob('*')
                   if p.is_file() and p.name != '.DS_Store'
                   and '__pycache__' not in p.parts
                   and p.suffix not in {'.class', '.pyc'})
    if not files:
        raise SystemExit('No code files have been delivered.')
    chunks, manifest = [], []
    for p in files:
        rel = p.relative_to(ROOT/'code').as_posix()
        old = BASE/rel
        before = old.read_text(encoding='utf-8') if old.exists() else ''
        after = p.read_text(encoding='utf-8')
        if before == after:
            continue
        delta = difflib.unified_diff(
            before.splitlines(keepends=True), after.splitlines(keepends=True),
            fromfile='a/'+rel if old.exists() else '/dev/null', tofile='b/'+rel, n=5)
        for line in delta:
            chunks.append(line if line.endswith('\n') else line+'\n\\ No newline at end of file\n')
        manifest.append({'path': rel, 'change': 'modified' if old.exists() else 'added',
                         'base_sha256': digest(old) if old.exists() else None,
                         'replacement_sha256': digest(p)})
    patch = ROOT/'fix.patch'
    patch.write_text(''.join(chunks), encoding='utf-8')
    if not manifest:
        raise SystemExit('No changes compared with baseline.')
    check = subprocess.run(['git', '-C', str(BASE), 'apply', '--check', str(patch)],
                           text=True, capture_output=True)
    (ROOT/'patch-check.json').write_text(json.dumps({
        'base_sha': head, 'changed_files': len(manifest),
        'patch_sha256': digest(patch), 'apply_check_exit': check.returncode,
        'stdout': check.stdout, 'stderr': check.stderr,
        'scope': 'Patch applicability only; this does not prove compilation or runtime correctness.'
    }, ensure_ascii=False, indent=2), encoding='utf-8')
    (ROOT/'source-manifest.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding='utf-8')
    print(json.dumps({'files':len(manifest), 'apply_check_exit':check.returncode,
                      'patch_bytes':patch.stat().st_size}))
    if check.returncode:
        raise SystemExit(check.returncode)

if __name__ == '__main__':
    main()
