#!/usr/bin/env python3
"""Download and verify the exact Vaultfire V3 bb0cf8b source archive."""
from __future__ import annotations

import hashlib
import json
import sys
import urllib.request
from pathlib import Path

BASE = "https://theloopbreaker.com/v3/releases/v3-source-2026-10-17-bb0cf8b"
INDEX = f"{BASE}/parts.json"


def digest(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def main() -> int:
    print(f"Downloading checksum-bound inventory: {INDEX}")
    with urllib.request.urlopen(INDEX, timeout=30) as response:
        inventory = json.load(response)
    output = Path(inventory["archive"])
    temporary = output.with_suffix(output.suffix + ".partial")
    total = 0
    with temporary.open("wb") as destination:
        for number, part in enumerate(inventory["parts"], 1):
            url = f"{BASE}/{part['path']}"
            print(f"[{number}/{len(inventory['parts'])}] {url}")
            with urllib.request.urlopen(url, timeout=60) as response:
                data = response.read()
            if len(data) != part["bytes"] or digest(data) != part["sha256"]:
                raise SystemExit(f"part verification failed: {part['path']}")
            destination.write(data)
            total += len(data)
    if total != inventory["byteLength"] or digest(temporary.read_bytes()) != inventory["sha256"]:
        temporary.unlink(missing_ok=True)
        raise SystemExit("final archive verification failed")
    temporary.replace(output)
    print(f"verified {output}: {total} bytes sha256={inventory['sha256']}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
