# MIT License
#
# Copyright (c) 2026 BitBlur
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""Verify the contents of a BitBlur asset ZIP without extracting it. Python 3.8+."""
import argparse
import hashlib
import json
import re
import stat
import sys
import zipfile
import zlib
from pathlib import Path

MAX_FILES = 20000
MAX_BYTES = 1024 ** 3
MAX_MANIFEST = 8 * 1024 ** 2
FORMATS = {"integrity.json": ("bitblur.file-integrity.v1", "name"),
           "download-manifest.json": ("bitblur.download/1", "path")}


def digest(stream):
    result = hashlib.sha256()
    for block in iter(lambda: stream.read(256 * 1024), b""):
        result.update(block)
    return result.hexdigest()


def valid_path(name):
    if not isinstance(name, str) or not name or "\\" in name or ":" in name:
        return False
    return all(part not in ("", ".", "..") for part in name.split("/")) and name.isprintable()


def inspect_archive(archive):
    infos = archive.infolist()
    if len(infos) > MAX_FILES or sum(info.file_size for info in infos) > MAX_BYTES:
        raise ValueError("Pack exceeds the size limit (20,000 entries or 1 GiB uncompressed).")
    files = {}
    seen = set()
    for info in infos:
        name = info.filename.rstrip("/") if info.is_dir() else info.filename
        if not valid_path(name) or info.orig_filename != info.filename:
            raise ValueError(f"Invalid archive path {info.filename!r}")
        if name.casefold() in seen:
            raise ValueError(f"Duplicate archive path {name!r}")
        seen.add(name.casefold())
        if info.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED):
            raise ValueError(f"Unsupported compression for {name!r}")
        if stat.S_ISLNK(info.external_attr >> 16) or info.flag_bits & 1:
            raise ValueError(f"Unsupported linked or encrypted entry {name!r}")
        if not info.is_dir():
            files[name] = info
    return files


def verify(path, expected_hash=None):
    with path.open("rb") as source:
        if expected_hash is not None:
            if not re.fullmatch("[0-9a-fA-F]{64}", expected_hash):
                raise ValueError("Expected a 64-character SHA-256 digest.")
            if digest(source) != expected_hash.lower():
                raise ValueError("ZIP SHA-256 differs from the expected digest.")
            source.seek(0)
        with zipfile.ZipFile(source) as archive:
            files = inspect_archive(archive)
            top = {name.split("/", 1)[0] for name in files}
            prefix = next(iter(top)) + "/" if len(top) == 1 and all("/" in n for n in files) else ""
            manifests = [name for name in FORMATS if prefix + name in files]
            if len(manifests) != 1:
                raise ValueError("Expected one integrity.json or download-manifest.json at the pack root.")
            manifest = manifests[0]
            info = files[prefix + manifest]
            if info.file_size > MAX_MANIFEST:
                raise ValueError("Manifest exceeds 8 MiB.")
            data = json.loads(archive.read(info))
            schema, field = FORMATS[manifest]
            if not isinstance(data, dict) or data.get("schema") != schema:
                raise ValueError("Unrecognised manifest schema.")
            records = data.get("files")
            if not isinstance(records, list) or not 0 < len(records) <= MAX_FILES:
                raise ValueError("Expected a nonempty list of file records.")
            verified = set()
            for row in records:
                if not isinstance(row, dict):
                    raise ValueError("Expected a file record.")
                name, size, sha = row.get(field), row.get("bytes"), row.get("sha256")
                if not valid_path(name) or name == manifest or name in verified:
                    raise ValueError(f"Invalid or repeated manifest entry {name!r}")
                if type(size) is not int or size < 0 or not isinstance(sha, str) or not re.fullmatch("[0-9a-fA-F]{64}", sha):
                    raise ValueError(f"Invalid size or SHA-256 for {name!r}")
                item = files.get(prefix + name)
                if item is None:
                    raise ValueError(f"Missing file {name!r}")
                if item.file_size != size:
                    raise ValueError(f"Wrong size for {name!r}")
                with archive.open(item) as stream:
                    if digest(stream) != sha.lower():
                        raise ValueError(f"SHA-256 mismatch for {name!r}")
                verified.add(name)
            extras = sorted(n[len(prefix):] for n in files if n != prefix + manifest and n[len(prefix):] not in verified)
            if extras:
                raise ValueError(f"Unexpected file {extras[0]!r}")
            return {"ok": True, "files": len(verified), "schema": schema,
                    "zipDigestVerified": expected_hash is not None}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("zip", type=Path)
    parser.add_argument("--sha256", help="Expected ZIP digest from a trusted release listing")
    parser.add_argument("--json", action="store_true", help="Print a machine-readable result")
    args = parser.parse_args()
    try:
        result = verify(args.zip, args.sha256)
    except (OSError, ValueError, RuntimeError, zipfile.BadZipFile, zlib.error, EOFError) as error:
        result = {"ok": False, "error": str(error)}
    if args.json:
        print(json.dumps(result))
    elif result["ok"]:
        print(f"Verified {result['files']} files against the manifest.")
    else:
        print(result["error"], file=sys.stderr)
    return 0 if result["ok"] else 1


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