#!/usr/bin/env python3
"""Pack every tool, source file and note under tools/ into download/nhl94-tools.zip.

Run after each release (deploy_local.py does it), so the site's single download always
matches the current ROM. Skips __pycache__; deterministic order and timestamps.
"""
from pathlib import Path
import json, subprocess, sys, zipfile

root = Path(__file__).resolve().parent.parent
tools = root / 'tools'
out = root / 'download' / 'nhl94-tools.zip'
meta = json.loads((tools / 'experimental' / 'release.json').read_text())
subprocess.run([sys.executable, str(tools / 'update_forum.py'), '--assets-only'], check=True)
tmp = out.with_suffix('.tmp')
files = sorted(p for p in tools.rglob('*') if p.is_file() and '__pycache__' not in p.parts)
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, compresslevel=9) as z:
    readme = (f"NHL 2026 - 94 Edition v5.1W - Season - jdc tools and sources, release {meta['version']}\n"
              f"ROM SHA256 {meta['sha256']}, CRC32 {meta['crc32']}\n\n"
              "Start with tools/notes/WORKFLOW.md and tools/notes/HACKING.md. Build the current ROM:\n"
              "  python3 tools/experimental/build_test.py 'NHL 2026 - 94 Edition v5.1W.bin' out.bin "
              f"--version {meta['version']}\n"
              "The base ROM (NHL 2026 - 94 Edition v5.1W.bin) is a separate download on the site.\n")
    zi = zipfile.ZipInfo('README.txt', (2026, 1, 1, 0, 0, 0)); zi.compress_type = zipfile.ZIP_DEFLATED
    z.writestr(zi, readme)
    for p in files:
        zi = zipfile.ZipInfo(str(p.relative_to(root)), (2026, 1, 1, 0, 0, 0))
        zi.compress_type = zipfile.ZIP_DEFLATED
        zi.external_attr = (p.stat().st_mode & 0o777) << 16
        z.writestr(zi, p.read_bytes())
tmp.replace(out)
print('tools zip', out, len(files), 'files', out.stat().st_size, 'bytes', meta['version'])
