"""Build a non-secret offline-tools handoff, not a full server recovery image."""
import hashlib
import json
import os
from pathlib import Path
import shutil
import tarfile

ROOT = Path(__file__).resolve().parent
OUTPUT = ROOT / "usb-kit-20260928-r03"


def sha(path):
    with path.open("rb") as stream:
        return hashlib.file_digest(stream, "sha256").hexdigest()


def main():
    if OUTPUT.exists():
        raise RuntimeError("Existing USB kit preserved")
    OUTPUT.mkdir(mode=0o755)
    chosen = {}
    for name in ("assets-manifest.json", "gui-manifest.json", "install_local_tools.py", "install_agent.py",
                 "install_commands.py", "install_gui.py", "install_maintenance.py", "install_acl.py",
                 "install_access.py", "finalize_tools.py",
                 "ct-llm", "ct-agent", "ct-gui", "ct_llm.py", "agent.py", "gui-session.sh", "system.ko.txt",
                 "stop_channels.py", "USB_README.ko.md"):
        chosen[name] = ROOT / name
    for directory in ("downloads", "gui-debs", "windows", "maintenance"):
        for p in (ROOT / directory).rglob("*"):
            if p.is_file() and not p.name.startswith("test_") and "__pycache__" not in p.parts and p.suffix!=".pyc":
                chosen[directory + "/" + str(p.relative_to(ROOT/directory))] = p
    for p in (ROOT/"crowd-0f172d94").rglob("*"):
        if p.is_file() and "__pycache__" not in p.parts:
            chosen["source/crowd-0f172d94/"+str(p.relative_to(ROOT/"crowd-0f172d94"))]=p
    chosen["source/icerti-crowd-20260928-r01.tar.gz"]=Path("/tmp/codex/ltb1021/2026-09-28_icerti-crowd-patch_r01/icerti-crowd-20260928-r01.tar.gz")
    records = json.loads((ROOT / "observability/verified-images.json").read_text())
    chosen["observability/images.json"] = ROOT / "observability/verified-images.json"
    chosen["observability/grafana-materialized/images.json"] = ROOT / "observability/images.json"
    for row in records["images"]:
        p = ROOT / "observability" / row["filename"]
        if sha(p) != row["sha256"] or p.stat().st_size != row["size_bytes"]:
            raise RuntimeError("Observability archive mismatch")
        key = "observability/" + ("grafana-materialized/" if row["tag"].startswith("grafana/") else "") + p.name
        chosen[key] = p
    total = sum(p.stat().st_size for p in chosen.values())
    if shutil.disk_usage(ROOT).free < 15*1024**3 + total:
        raise RuntimeError("USB tar would violate root reserve")
    rows = []
    for relative, path in sorted(chosen.items()):
        if path.is_symlink() or not path.is_file():
            raise RuntimeError("Only reviewed regular files allowed")
        target = OUTPUT / relative
        target.parent.mkdir(parents=True, exist_ok=True)
        os.link(path, target)
        rows.append(dict(path=relative, bytes=path.stat().st_size, sha256=sha(path)))
    manifest = dict(schema=1, purpose="offline-tools-handoff", field="icerti", files=rows,
                    total_bytes=total, contains_secrets=False, full_server_recovery=False,
                    excluded=["GGUF model", "Contextra full runtime/model engines", "private keys/passwords/tokens", "DB/ledger/media"])
    (OUTPUT / "MANIFEST.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
    (OUTPUT / "SHA256SUMS").write_text("".join(row["sha256"] + "  " + row["path"] + "\n" for row in rows))
    archive_path = ROOT / "contextra-offline-tools-20260928-r03.tar"
    with tarfile.open(archive_path, "w", dereference=True) as archive:
        for path in sorted(OUTPUT.rglob("*")):
            if path.is_file():
                archive.add(path, arcname=str(Path(OUTPUT.name) / path.relative_to(OUTPUT)), recursive=False)
    (ROOT / (archive_path.name + ".sha256")).write_text(sha(archive_path) + "  " + archive_path.name + "\n")
    print(json.dumps(dict(archive=str(archive_path), bytes=archive_path.stat().st_size,
                         files=len(rows), sha256=sha(archive_path)), indent=2))


if __name__ == "__main__":
    main()
