"""Verify the published synthetic example. No extraction, execution or network access.

Consistency checks only: obtain the checksum through a trusted channel. This is not
a general AuditFetch signature verifier or a source-authentication mechanism.
"""

import hashlib
import json
from pathlib import Path, PurePosixPath
import re
import sys
import zipfile

LIMIT = 2 * 1024 * 1024


def verify(packet, checksum):
    packet, checksum = Path(packet), Path(checksum)
    if packet.stat().st_size > LIMIT or checksum.stat().st_size > 1024:
        raise ValueError("File exceeds the sample size limit")
    match = re.fullmatch(r"([a-f0-9]{64})  ([^\r\n]+)\n?", checksum.read_text())
    if not match or match[2] != packet.name:
        raise ValueError("Invalid checksum entry or packet filename")
    if hashlib.sha256(packet.read_bytes()).hexdigest() != match[1]:
        raise ValueError("Packet checksum mismatch")
    with zipfile.ZipFile(packet) as archive:
        entries = archive.infolist()
        names = [entry.filename for entry in entries]
        if len(names) > 32 or len(names) != len(set(names)):
            raise ValueError("Too many or duplicate archive entries")
        if sum(entry.file_size for entry in entries) > LIMIT:
            raise ValueError("Expanded sample is too large")
        for name in names:
            path = PurePosixPath(name)
            if path.is_absolute() or ".." in path.parts or "\\" in name:
                raise ValueError("Unsafe archive path")
        manifest = json.loads(archive.read("manifest.json"))
        artifacts = manifest["artifacts"]
        if not isinstance(artifacts, list) or len(artifacts) != 1:
            raise ValueError("Expected one synthetic artifact")
        if manifest["artifact_count"] != len(artifacts):
            raise ValueError("Artifact count mismatch")
        expected = {"manifest.json", "manifest.csv"}
        for artifact in artifacts:
            name = artifact["archive_path"]
            if not isinstance(name, str) or not name.startswith("artifacts/"):
                raise ValueError("Invalid artifact path")
            data = archive.read(name)
            if len(data) != artifact["size_bytes"]:
                raise ValueError("Artifact size mismatch")
            if hashlib.sha256(data).hexdigest() != artifact["content_hash"]:
                raise ValueError("Artifact content hash mismatch")
            if json.loads(data).get("sample") is not True:
                raise ValueError("Synthetic sample label missing")
            expected.add(name)
        if set(names) != expected:
            raise ValueError("Unexpected or missing archive entry")


if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit("Usage: python3 verify_sample_packet.py PACKET.zip PACKET.SHA256SUMS")
    try:
        verify(sys.argv[1], sys.argv[2])
    except (OSError, ValueError, KeyError, TypeError, zipfile.BadZipFile, RuntimeError) as error:
        sys.exit("Verification failed: " + str(error))
    print("Synthetic packet and payload checks passed. This is not an audit verdict.")
