"""Byte-only source/evidence packaging. Never connects or executes application code."""
import hashlib, json, os, pathlib, shutil, sys, tarfile

HERE = pathlib.Path(__file__).resolve().parent
WORK = pathlib.Path('/Users/wiscourper/Documents/workspace/zhct')
MATRIX = WORK / 'zhctprompt/work/2026-09-28-smart-canteen-dm8-poc/matrix-integration'
OUT = pathlib.Path('/tmp/cdx-prepay-code-scan-chain-package-20261011')

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

def copy(source, target):
    assert source.is_file() and not source.is_symlink(), str(source)
    target.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    shutil.copyfile(source, target)
    os.chmod(target, 0o600)
    assert digest(source) == digest(target)

def build():
    assert not OUT.exists(), 'Exclusive new package; never overwrite/rebuild an attempted runtime'
    OUT.mkdir(mode=0o700)
    store = json.loads((MATRIX/'STORE_APPLICATION_20261011_1034.json').read_text())
    ai = json.loads((MATRIX/'AI_RUNTIME_SOURCE_20261011_1230.json').read_text())['files']
    assert len(store) == 959 and len(ai) == 6169
    for role, root, pins in [('store', WORK/'zhctproject/store/application', store), ('ai', WORK/'zhctproject/ai_api', ai)]:
        for name, sha in pins.items():
            assert not name.startswith('/') and '..' not in pathlib.PurePosixPath(name).parts
            source = root/name
            assert digest(source) == sha, 'Source drift '+name
            copy(source, OUT/'source'/role/name)
        (OUT/(role+'-pins.json')).write_text(json.dumps(pins,ensure_ascii=False,separators=(',',':')))
        os.chmod(OUT/(role+'-pins.json'),0o600)
    proposal = HERE.parent
    copy(proposal/'machine-plan.json', OUT/'machine-plan.json')
    assert digest(OUT/'machine-plan.json') == '2cbf71e15720fb654b963bbea7f2556b2711177cd573e714670248e11cc5f1e5'
    fresh = proposal.parent/'fresh-readonly-20261011'
    for side in ['B','C']:
        private = OUT/'private-input'/side
        copy(fresh/('plan-'+side+'.json'), private/'fresh-plan.json')
        copy(pathlib.Path('/tmp/cdx-prepay-code-scan-fresh-package-20261011')/('baseline-'+side+'.json'), private/'baseline.json')
        ev = pathlib.Path('/tmp/cdx-prepay-code-scan-fresh-'+side+'-evidence-20261011')
        copy(ev/'private-request-plan.json',private/'accepted-signature.json')
        records = {}
        for line in (ev/'events.jsonl').open():
            event = json.loads(line)
            if event.get('event') == 'original-read-result':
                records[event['statement']['label']] = event
        file = private/'fresh-records.json'
        file.write_text(json.dumps(records,ensure_ascii=False,separators=(',',':')))
        os.chmod(file,0o600)
    for file in HERE.iterdir():
        if file.is_file() and file.suffix == '.php': copy(file,OUT/'tools'/file.name)
    archive = OUT.with_suffix('.tar')
    assert not archive.exists()
    with tarfile.open(archive,'w',format=tarfile.USTAR_FORMAT) as tar:
        for file in sorted(OUT.rglob('*')):
            if file.is_file():
                info = tar.gettarinfo(str(file),str(file.relative_to(OUT)))
                info.uid=info.gid=0; info.uname=info.gname=''; info.mode=0o600
                with file.open('rb') as data: tar.addfile(info,data)
    os.chmod(archive,0o600)
    print(json.dumps({'status':'BYTE_ONLY_PACKAGE','Store':len(store),'AI':len(ai),'archive_bytes':archive.stat().st_size,'archive_sha256':digest(archive),'DB':0,'SQL':0}))

if __name__ == '__main__': build()
