"""Usage: python3 assemble-export.py companion-ID.manifest.json"""
import hashlib
import json
from pathlib import Path
import sys
import uuid


def assemble(manifest_path):
    manifest_path = Path(manifest_path)
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    snapshot_id = str(uuid.UUID(manifest["snapshot_id"]))
    if manifest["format_version"] != 2 or manifest["complete_snapshot"] is not True:
        raise ValueError("Not a complete snapshot manifest")
    total = manifest["part_count"]
    if not isinstance(total, int) or total < 1:
        raise ValueError("Invalid part count")
    output = manifest_path.parent / f"companion-{snapshot_id}.jsonl"
    temporary = output.with_suffix(".assembling")
    size = 0
    records = 0
    complete_digest = hashlib.sha256()
    created = False
    try:
        with temporary.open("xb") as target:
            created = True
            for part in range(1, total + 1):
                path = manifest_path.parent / f"companion-{snapshot_id}.part{part:08d}"
                digest = hashlib.sha256()
                with path.open("rb") as source:
                    while block := source.read(65536):
                        digest.update(block)
                        complete_digest.update(block)
                        records += block.count(b"\n")
                        size += len(block)
                        target.write(block)
                expected = manifest.get("requested_part_sha256", {}).get(str(part))
                if expected and digest.hexdigest() != expected:
                    raise ValueError(f"Part {part} failed SHA-256 verification")
        if size != manifest["byte_count"]:
            raise ValueError("Byte count does not match; copy is incomplete")
        if complete_digest.hexdigest() != manifest["sha256"]:
            raise ValueError("Complete snapshot failed SHA-256 verification")
        if records != manifest["record_count"] + 1:
            raise ValueError("Record count does not match; copy is incomplete")
        if output.exists():
            raise ValueError(f"Output already exists: {output}")
        temporary.rename(output)
        return output
    finally:
        if created:
            temporary.unlink(missing_ok=True)


if __name__ == "__main__":
    try:
        print(f"Complete snapshot verified: {assemble(sys.argv[1])}")
    except (OSError, ValueError, KeyError, IndexError) as error:
        sys.exit(f"Not verified: {error}")
