import datetime
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys


ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / 'Contextra_Offline_USB_20261103_r01'
EXPORT = ROOT.parent / '2026-11-03_contextra-offline-export_r01'


def main():
    result = json.loads((ROOT / 'reports/delivery-finalization.json').read_bytes())
    command = subprocess.run(['/usr/bin/unshare', '--net', '/usr/bin/sha256sum', '-c',
                              'BOOTSTRAP_SHA256SUMS'], cwd=OUT, capture_output=True, text=True, timeout=60)
    if command.returncode:
        raise RuntimeError('Bootstrap payload check failed')
    md_files = sorted(OUT.glob('*.md'))
    links = 0
    shell_blocks = 0
    for path in md_files:
        text = path.read_text()
        if re.search(r'@[A-Z_]+@', text):
            raise RuntimeError('Template token remains')
        for target in re.findall(r'\]\(([^)]+)\)', text):
            if '://' in target or target.startswith('#'):
                continue
            if not (path.parent / target.split('#', 1)[0]).is_file():
                raise RuntimeError('Local guide link missing: ' + target)
            links += 1
        for code in re.findall(r'```bash\n(.*?)```', text, flags=re.S):
            parsed = subprocess.run(['/bin/bash', '-n'], input=code, text=True,
                                    capture_output=True, timeout=10)
            if parsed.returncode:
                raise RuntimeError('Guide shell syntax failed: ' + path.name)
            shell_blocks += 1
    manifest = json.loads((OUT / 'package/package.json').read_bytes())
    full = {}
    for line in (OUT / 'SHA256SUMS').read_text().splitlines():
        digest, name = line.split('  ', 1)
        if name in full:
            raise RuntimeError('Duplicate checksum path')
        full[name] = digest
    actual = {p.relative_to(OUT).as_posix() for p in OUT.rglob('*') if p.is_file()}
    if actual != set(full) | {'SHA256SUMS', 'BOOTSTRAP_SHA256SUMS'}:
        raise RuntimeError('Delivery file set changed')
    for name, info in manifest['files'].items():
        if full['package/' + name] != info['sha256']:
            raise RuntimeError('Checksum catalog mismatch')
    if hashlib.sha256((OUT / 'BOOTSTRAP_SHA256SUMS').read_bytes()).hexdigest() != result['bootstrap_sha256']:
        raise RuntimeError('Bootstrap catalog changed')
    sys.path.insert(0, str(EXPORT / 'helpers'))
    from prepare_evidence import snapshot
    env_before = os.environ.get('DOCKER_HOST')
    os.environ['DOCKER_HOST'] = 'unix:///var/run/docker.sock'
    try:
        final = snapshot()
    finally:
        if env_before is None:
            os.environ.pop('DOCKER_HOST', None)
        else:
            os.environ['DOCKER_HOST'] = env_before
    first = json.loads((ROOT / 'reports/before.json').read_bytes())
    if final['containers'] != first['containers'] or final['files'] != first['files']:
        raise RuntimeError('Operational state changed; review before handoff')
    (ROOT / 'reports/final-state.json').write_text(json.dumps(final, indent=2) + '\n')
    result.update(status='READY_FOR_USER_MANUAL_TEST',
                  timestamp=datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).isoformat(),
                  bootstrap_check='PASS', shell_syntax_blocks=shell_blocks, local_links=links,
                  markdown_files=len(md_files), exact_delivery_file_set=True,
                  operation_state_unchanged=True, root_free=final['free']['/'],
                  data_free=final['free']['/data'], full_archive_readback='sealed-package.json',
                  actual_apply=False, actual_rollback=False, cold_load=False,
                  browser_acceptance=False, fps_acceptance=False)
    (ROOT / 'reports/final-validation.json').write_text(json.dumps(result, indent=2) + '\n')
    print(json.dumps(result))


if __name__ == '__main__':
    main()
