"""Reassemble one pinned original archive without changing its bytes."""
import argparse
import hashlib
import json
from pathlib import Path

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source_id")
parser.add_argument("destination", type=Path)
args = parser.parse_args()
root = Path(__file__).resolve().parent
manifest = json.loads((root / "SOURCE-MANIFEST.json").read_text(encoding="utf-8"))
entry = next(item for item in manifest["sources"] if item["id"] == args.source_id)
args.destination.parent.mkdir(parents=True, exist_ok=True)
whole = hashlib.sha256()
size = 0
try:
    with args.destination.open("xb") as output:
        for part in entry["published_files"]:
            filename = root / part["path"]
            part_hash = hashlib.sha256()
            count = 0
            with filename.open("rb") as stream:
                for block in iter(lambda: stream.read(1024 * 1024), b""):
                    count += len(block)
                    part_hash.update(block)
                    whole.update(block)
                    output.write(block)
            if count != part["size"] or part_hash.hexdigest() != part["sha256"]:
                raise ValueError("Part checksum mismatch: " + part["path"])
            size += count
        if size != entry["size"] or whole.hexdigest() != entry["sha256"]:
            raise ValueError("Reassembled archive checksum mismatch")
except FileExistsError:
    raise SystemExit("Destination already exists; choose a new path")
except Exception:
    args.destination.unlink(missing_ok=True)
    raise
print("Verified original archive:", args.destination, whole.hexdigest())
