"""Construiește arhiva publică, deterministă, pentru audit și reproducere."""

from __future__ import annotations

import hashlib
import os
import shutil
import zipfile
from pathlib import Path


ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / "public" / "downloads"
ARCHIVE = OUT / "straturi-source.zip"
FIXED_TIME = (2026, 7, 30, 0, 0, 0)

ROOT_FILES = (
    "README.md",
    "RESEARCH_NOTES.md",
    "AUDIT.md",
    "REPRODUCERE.md",
    "DEXONLINE-NOTICE.md",
    "build.mjs",
    "worker.js",
    "qa_assertions.mjs",
    "wrangler.jsonc",
)


def files() -> list[Path]:
    selected = [ROOT / name for name in ROOT_FILES]
    selected.extend(sorted((ROOT / "tools").glob("*.py")))
    selected.append(ROOT / "tools" / "overrides.json")
    selected.append(ROOT / "tools" / "serve.mjs")
    selected.append(ROOT / "content" / "copy.mjs")
    selected.extend(sorted((ROOT / "content" / "data").rglob("*.json")))
    selected.extend(
        sorted(path for path in (ROOT / "public" / "assets").rglob("*")
               if path.is_file())
    )
    return selected


def add(zf: zipfile.ZipFile, path: Path) -> None:
    rel = Path("straturi") / path.relative_to(ROOT)
    info = zipfile.ZipInfo(rel.as_posix(), FIXED_TIME)
    info.compress_type = zipfile.ZIP_DEFLATED
    info.external_attr = (0o644 & 0xFFFF) << 16
    zf.writestr(info, path.read_bytes(), compresslevel=9)


def main() -> None:
    OUT.mkdir(parents=True, exist_ok=True)
    with zipfile.ZipFile(ARCHIVE, "w") as zf:
        for path in files():
            if not path.is_file():
                raise FileNotFoundError(path)
            add(zf, path)
    digest = hashlib.sha256(ARCHIVE.read_bytes()).hexdigest()
    checksum = OUT / "straturi-source.sha256"
    checksum.write_text(f"{digest}  {ARCHIVE.name}\n", encoding="ascii")
    for pattern in ("straturi-source-*.zip", "straturi-source-*.sha256"):
        for stale in OUT.glob(pattern):
            stale.unlink()
    version = digest[:12]
    versioned_archive = OUT / f"straturi-source-{version}.zip"
    versioned_checksum = OUT / f"straturi-source-{version}.sha256"
    shutil.copyfile(ARCHIVE, versioned_archive)
    versioned_checksum.write_text(
        f"{digest}  {versioned_archive.name}\n", encoding="ascii"
    )
    size = os.path.getsize(ARCHIVE)
    print(f"arhivă reproducere: {ARCHIVE.name}, {size:,} bytes, sha256 {digest}")


if __name__ == "__main__":
    main()
