#!/usr/bin/env python3
"""Verify this corpus using only Python's standard library; never uses network."""
import argparse
import hashlib
import json
import os
import re
import shutil
import tempfile
from pathlib import Path, PurePosixPath

ROOT = Path(__file__).resolve().parent
SHA256_RE = re.compile(r"^[0-9a-f]{64}$")


def _under(path: Path, root: Path) -> bool:
    try:
        path.relative_to(root)
        return True
    except ValueError:
        return False


def _safe_regular_file(root: Path, relative: str) -> tuple[Path | None, str | None]:
    """Resolve a POSIX manifest path without traversing symlinks."""
    if not isinstance(relative, str) or not relative or "\\" in relative:
        return None, f"unsafe manifest path: {relative!r}"
    pure = PurePosixPath(relative)
    if pure.is_absolute() or any(part in ("", ".", "..") for part in pure.parts):
        return None, f"unsafe manifest path: {relative!r}"
    path = root
    for part in pure.parts:
        path = path / part
        try:
            if path.is_symlink():
                return None, f"symlink path component not allowed: {relative}"
        except OSError as exc:
            return None, f"cannot inspect path {relative}: {exc}"
    resolved = path.resolve(strict=False)
    if not _under(resolved, root):
        return None, f"path outside bundle root: {relative}"
    if not path.is_file():
        return None, f"missing or non-regular file: {relative}"
    return path, None


def _validate_manifest(manifest: object) -> tuple[list[dict] | None, list[str]]:
    errors: list[str] = []
    if not isinstance(manifest, dict):
        return None, ["manifest must be a JSON object"]

    required_strings = ("schema_version", "corpus_id", "corpus_version", "created_at", "title", "description")
    for key in required_strings:
        if not isinstance(manifest.get(key), str) or not manifest[key].strip():
            errors.append(f"manifest field {key!r} must be a non-empty string")

    provenance = manifest.get("provenance")
    if not isinstance(provenance, dict):
        errors.append("manifest field 'provenance' must be an object")
    else:
        for key in ("author", "origin"):
            if not isinstance(provenance.get(key), str) or not provenance[key].strip():
                errors.append(f"provenance field {key!r} must be a non-empty string")
        if not isinstance(provenance.get("synthetic"), bool):
            errors.append("provenance field 'synthetic' must be a boolean")

    license_info = manifest.get("license")
    if not isinstance(license_info, dict):
        errors.append("manifest field 'license' must be an object")
    else:
        for key in ("name", "url", "notice"):
            if not isinstance(license_info.get(key), str) or not license_info[key].strip():
                errors.append(f"license field {key!r} must be a non-empty string")

    entries = manifest.get("files")
    if not isinstance(entries, list) or not entries:
        errors.append("manifest field 'files' must be a non-empty array")
        return None, errors

    seen: set[str] = set()
    valid_entries: list[dict] = []
    for index, entry in enumerate(entries):
        if not isinstance(entry, dict):
            errors.append(f"files[{index}] must be an object")
            continue
        rel = entry.get("path")
        if not isinstance(rel, str) or not rel:
            errors.append(f"files[{index}].path must be a non-empty string")
            continue
        normalized = PurePosixPath(rel).as_posix()
        if normalized in seen:
            errors.append(f"duplicate manifest path: {rel}")
        seen.add(normalized)
        for key in ("title", "media_type"):
            if not isinstance(entry.get(key), str) or not entry[key].strip():
                errors.append(f"files[{index}].{key} must be a non-empty string")
        size = entry.get("bytes")
        if isinstance(size, bool) or not isinstance(size, int) or size < 0:
            errors.append(f"files[{index}].bytes must be a non-negative integer")
        digest = entry.get("sha256")
        if not isinstance(digest, str) or not SHA256_RE.fullmatch(digest):
            errors.append(f"files[{index}].sha256 must be 64 lowercase hexadecimal characters")
        valid_entries.append(entry)
    return valid_entries, errors


def verify(root: Path, expected_manifest_sha256: str | None = None) -> list[str]:
    errors: list[str] = []
    root = Path(root).absolute()
    for component in (root, *root.parents):
        if component.is_symlink():
            return [f"bundle root or parent must not be a symlink: {component}"]
    try:
        resolved_root = root.resolve(strict=True)
    except OSError as exc:
        return [f"cannot access bundle root: {exc}"]
    if not resolved_root.is_dir():
        return ["bundle root is not a directory"]

    # A symlink at corpus/ is especially easy to miss: os.walk follows a
    # symlink supplied as its starting directory even with followlinks=False.
    corpus = resolved_root / "corpus"
    if corpus.is_symlink():
        errors.append("symlink corpus directory is not allowed")
    elif not corpus.is_dir():
        errors.append("corpus directory is missing or not a directory")

    manifest_path, path_error = _safe_regular_file(resolved_root, "manifest.json")
    if path_error:
        return errors + [path_error]
    try:
        raw = manifest_path.read_bytes()
        manifest = json.loads(raw)
    except (OSError, UnicodeError, json.JSONDecodeError) as exc:
        return errors + [f"cannot read manifest.json: {exc}"]

    actual_manifest_hash = hashlib.sha256(raw).hexdigest()
    sidecar_path, sidecar_error = _safe_regular_file(resolved_root, "manifest.sha256")
    if sidecar_error:
        errors.append(sidecar_error)
    else:
        try:
            sidecar_text = sidecar_path.read_text(encoding="ascii").strip()
            fields = sidecar_text.split()
            if (len(fields) not in (1, 2) or not SHA256_RE.fullmatch(fields[0])
                    or (len(fields) == 2 and fields[1] != "manifest.json")):
                errors.append("manifest.sha256 must contain one lowercase SHA-256 digest, optionally followed by 'manifest.json'")
            elif fields[0] != actual_manifest_hash:
                errors.append("manifest.json SHA-256 does not match manifest.sha256")
        except (OSError, UnicodeError) as exc:
            errors.append(f"cannot read manifest.sha256: {exc}")

    if expected_manifest_sha256 is not None:
        if not isinstance(expected_manifest_sha256, str) or not SHA256_RE.fullmatch(expected_manifest_sha256):
            errors.append("separately saved manifest digest must be 64 lowercase hexadecimal characters")
        elif expected_manifest_sha256 != actual_manifest_hash:
            errors.append("manifest.json SHA-256 does not match the separately saved digest")

    entries, shape_errors = _validate_manifest(manifest)
    errors.extend(shape_errors)
    if entries is None:
        return errors

    declared: set[str] = set()
    for entry in entries:
        rel = entry.get("path")
        if not isinstance(rel, str) or not rel:
            continue
        path, error = _safe_regular_file(resolved_root, rel)
        if error:
            errors.append(error)
            continue
        posix = PurePosixPath(rel).as_posix()
        declared.add(posix)
        # Corpus manifests must only describe files below corpus/.
        if not posix.startswith("corpus/"):
            errors.append(f"manifest path is outside corpus/: {posix}")
            continue
        data = path.read_bytes()
        if isinstance(entry.get("bytes"), int) and not isinstance(entry.get("bytes"), bool):
            if len(data) != entry["bytes"]:
                errors.append(f"byte size mismatch: {posix} (got {len(data)}, expected {entry['bytes']})")
        if isinstance(entry.get("sha256"), str) and SHA256_RE.fullmatch(entry["sha256"]):
            if hashlib.sha256(data).hexdigest() != entry["sha256"]:
                errors.append(f"SHA-256 mismatch: {posix}")

    actual: set[str] = set()
    if corpus.is_dir() and not corpus.is_symlink():
        for base, dirs, files in os.walk(corpus, followlinks=False):
            base_path = Path(base)
            for name in dirs:
                item = base_path / name
                if item.is_symlink():
                    errors.append(f"symlink directory not allowed: {item.relative_to(resolved_root)}")
            for name in files:
                item = base_path / name
                if item.is_symlink():
                    errors.append(f"symlink file not allowed: {item.relative_to(resolved_root)}")
                elif item.is_file():
                    actual.add(item.relative_to(resolved_root).as_posix())
    if actual != declared:
        for name in sorted(declared - actual):
            errors.append(f"declared file not found in corpus: {name}")
        for name in sorted(actual - declared):
            errors.append(f"undeclared extra file: {name}")
    return errors


def _refresh_sidecar(root: Path) -> None:
    raw = (root / "manifest.json").read_bytes()
    (root / "manifest.sha256").write_text(hashlib.sha256(raw).hexdigest() + "\n", encoding="ascii")


def _expect_failure(label: str, root: Path, needles: tuple[str, ...]) -> bool:
    errors = verify(root)
    if any(all(needle in error for needle in needles) for error in errors):
        print(f"PASS: {label}")
        return True
    print(f"FAIL: {label}; got: {errors}")
    return False


def self_test() -> int:
    failures = []
    entries = json.loads((ROOT / "manifest.json").read_text(encoding="utf-8")).get("files", [])
    if not entries or not isinstance(entries[0].get("path"), str):
        print("FAIL: self-test needs at least one declared corpus file")
        return 1
    changed_rel = entries[0]["path"]
    with tempfile.TemporaryDirectory(prefix="mesh-recovery-test-") as tmp:
        base = Path(tmp)

        changed = base / "changed"
        shutil.copytree(ROOT, changed)
        target = changed / changed_rel
        target.write_bytes(target.read_bytes() + b"\n")
        failures.append(not _expect_failure("detects deliberate changed file", changed, (f"SHA-256 mismatch: {changed_rel}",)))

        symlinked = base / "symlinked"
        shutil.copytree(ROOT, symlinked)
        external = base / "external-corpus"
        shutil.copytree(symlinked / "corpus", external)
        shutil.rmtree(symlinked / "corpus")
        try:
            (symlinked / "corpus").symlink_to(external, target_is_directory=True)
            failures.append(not _expect_failure("rejects symlinked corpus directory", symlinked, ("symlink corpus directory",)))
        except (OSError, NotImplementedError):
            print("SKIP: platform does not permit symlink self-test")

        malformed = base / "malformed"
        shutil.copytree(ROOT, malformed)
        manifest_path = malformed / "manifest.json"
        manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
        manifest["files"][1]["sha256"] = "not-a-digest"
        manifest["files"].append(dict(manifest["files"][0]))
        manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
        _refresh_sidecar(malformed)
        malformed_errors = verify(malformed)
        duplicate_ok = any("duplicate manifest path" in error for error in malformed_errors)
        digest_ok = any("sha256 must be 64 lowercase hexadecimal" in error for error in malformed_errors)
        if duplicate_ok and digest_ok:
            print("PASS: rejects duplicate path and malformed SHA-256 digest")
        else:
            print(f"FAIL: duplicate/digest validation; got: {malformed_errors}")
            failures.append(True)

        malformed_cases = (
            ("non-object manifest", lambda _manifest: [], "manifest must be a JSON object"),
            ("non-object file entry", lambda manifest: {**manifest, "files": [None]}, "files[0] must be an object"),
            ("non-string file path", lambda manifest: {**manifest, "files": [{**manifest["files"][0], "path": 7}]}, "files[0].path must be a non-empty string"),
        )
        for index, (label, mutate, expected_error) in enumerate(malformed_cases):
            bad_root = base / f"malformed-shape-{index}"
            shutil.copytree(ROOT, bad_root)
            bad_manifest_path = bad_root / "manifest.json"
            original_manifest = json.loads(bad_manifest_path.read_text(encoding="utf-8"))
            bad_manifest_path.write_text(json.dumps(mutate(original_manifest), indent=2) + "\n", encoding="utf-8")
            _refresh_sidecar(bad_root)
            failures.append(not _expect_failure(f"rejects {label}", bad_root, (expected_error,)))

        external_digest = hashlib.sha256((ROOT / "manifest.json").read_bytes()).hexdigest()
        if verify(ROOT, external_digest):
            print("FAIL: accepts correct separately saved digest")
            failures.append(True)
        else:
            print("PASS: accepts matching separately saved manifest digest")
        if not verify(ROOT, "0" * 64):
            print("FAIL: rejects mismatched separately saved digest")
            failures.append(True)
        else:
            print("PASS: rejects mismatched separately saved manifest digest")

    return 1 if any(failures) else 0


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--expected-manifest-sha256", help="compare against a separately saved digest; this does not authenticate its publisher")
    parser.add_argument("--self-test", action="store_true", help="run disposable positive/negative verifier checks")
    args = parser.parse_args()
    if args.self_test:
        return self_test()
    failures = verify(ROOT, args.expected_manifest_sha256)
    if failures:
        print("FAIL: corpus verification found problems")
        for failure in failures:
            print(f"- {failure}")
        return 1
    print("PASS: manifest, corpus file set, byte sizes, and SHA-256 digests match")
    if args.expected_manifest_sha256:
        print("PASS: manifest also matches the separately saved digest")
    return 0


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