#!/usr/bin/env python3
"""Create a deterministic direct-deployment ZIP from the verified build tree."""
import os
import sys
import zipfile
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
SOURCE = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else ROOT / 'build'
OUTPUT = Path(sys.argv[2]).resolve() if len(sys.argv) > 2 else ROOT / 'GLMCHAT_V2.0.1_DIRECT_DEPLOY_READY_OFFLINE_VERIFIED.zip'
STAMP = (2026, 7, 18, 0, 0, 0)

if not (SOURCE / 'build-manifest.json').is_file():
    raise SystemExit('Verified build-manifest.json is missing.')
if OUTPUT.exists():
    OUTPUT.unlink()

files = []
for path in SOURCE.rglob('*'):
    if path.is_symlink():
        raise SystemExit(f'Symlink prohibited: {path}')
    if path.is_file():
        files.append(path)

with zipfile.ZipFile(OUTPUT, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9, strict_timestamps=True) as archive:
    for path in sorted(files, key=lambda item: item.relative_to(SOURCE).as_posix()):
        relative = path.relative_to(SOURCE).as_posix()
        info = zipfile.ZipInfo(relative, STAMP)
        info.create_system = 3
        mode = 0o755 if os.access(path, os.X_OK) else 0o644
        info.external_attr = (mode & 0xFFFF) << 16
        info.compress_type = zipfile.ZIP_DEFLATED
        with path.open('rb') as source:
            archive.writestr(info, source.read(), compress_type=zipfile.ZIP_DEFLATED, compresslevel=9)
print(OUTPUT)
