#!/usr/bin/env python3
"""Reconstruct a checksum-bound, unsigned Vaultfire source-review archive."""
from __future__ import annotations

import argparse
import hashlib
import json
import re
import urllib.request
from pathlib import Path
from urllib.parse import urlparse

BASE = "https://theloopbreaker.com/v3/releases/v3-source-oct26-385415d1"
SHA = re.compile(r"^[a-f0-9]{64}$")
NAME = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]*$")


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--base-url", default=BASE, help="HTTPS release URL; HTTP is allowed only on loopback for local QA")
    args = parser.parse_args()
    base = args.base_url.rstrip("/")
    parsed = urlparse(base)
    if parsed.username or parsed.password or parsed.query or parsed.fragment:
        raise SystemExit("base URL must not contain credentials, query or fragment")
    if parsed.scheme != "https" and not (
        parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1", "::1"}
    ):
        raise SystemExit("HTTPS required except for an explicit loopback QA URL")
    with urllib.request.urlopen(f"{base}/parts.json", timeout=30) as response:
        raw = response.read(2 * 1024 * 1024 + 1)
    if len(raw) > 2 * 1024 * 1024:
        raise SystemExit("inventory exceeds bounded size")
    inventory = json.loads(raw)
    name = inventory.get("archive", "")
    parts = inventory.get("parts", [])
    total = inventory.get("byteLength")
    if (
        inventory.get("schema") != "vaultfire.multipart-source-archive.v1"
        or not NAME.fullmatch(name)
        or not SHA.fullmatch(inventory.get("sha256", ""))
        or type(total) is not int or total <= 0
        or not isinstance(parts, list) or not 1 <= len(parts) <= 4096
    ):
        raise SystemExit("invalid archive inventory")
    seen = set()
    declared = 0
    for part in parts:
        relative = part.get("path", "")
        basename = relative.removeprefix("parts/")
        size = part.get("bytes")
        if (
            not relative.startswith("parts/") or not NAME.fullmatch(basename)
            or relative in seen or type(size) is not int or not 0 < size <= 4 * 1024 * 1024
            or not SHA.fullmatch(part.get("sha256", ""))
        ):
            raise SystemExit("invalid or duplicate part")
        seen.add(relative)
        declared += size
    if declared != total:
        raise SystemExit("part sizes do not equal the archive size")
    output = Path(name)
    temporary = Path(f"{name}.partial")
    if output.exists():
        raise SystemExit("refusing to overwrite an existing archive")
    archive_hash = hashlib.sha256()
    written = 0
    created = False
    try:
        with temporary.open("xb") as destination:
            created = True
            for index, part in enumerate(parts, 1):
                part_hash = hashlib.sha256()
                part_written = 0
                with urllib.request.urlopen(f"{base}/{part['path']}", timeout=60) as response:
                    while chunk := response.read(1024 * 1024):
                        part_written += len(chunk)
                        if part_written > part["bytes"]:
                            raise ValueError("part exceeds its declared size")
                        part_hash.update(chunk)
                        archive_hash.update(chunk)
                        destination.write(chunk)
                if part_written != part["bytes"] or part_hash.hexdigest() != part["sha256"]:
                    raise ValueError(f"part verification failed: {part['path']}")
                written += part_written
                print(f"[{index}/{len(parts)}] verified {part['path']}")
            if written != total or archive_hash.hexdigest() != inventory["sha256"]:
                raise ValueError("final archive verification failed")
        # Exclusive link creation does not overwrite a file created during the download.
        output.hardlink_to(temporary)
        temporary.unlink()
        created = False
    finally:
        if created:
            temporary.unlink(missing_ok=True)
    print(f"verified {output}: {written} bytes sha256={archive_hash.hexdigest()}")
    print("Checksums establish byte integrity, not independent audit or publication authority.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
