#!/usr/bin/env python3
"""Validate the trust_matrix block on every MCP reference metadata file.

The trust_matrix field is optional in the schema today (graceful rollout),
but this validator enforces it on every file currently committed under
mcp/. New entries that lack trust_matrix fail this check, which prevents
regressions and steers contributors to declare the security-relevant
posture explicitly.

Promotes to a required field in the schema once the corpus and
contribution guide have been updated. Until then, this validator is the
de-facto contract.
"""

from __future__ import annotations

import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]

REQUIRED_TM_FIELDS = {
    "mutation_capable",
    "requires_egress",
    "requires_credentials",
    "signed_release",
    "pin_strategy",
}
ALLOWED_SIGNED = {"cosign", "gh-attestation", "unsigned", "unknown"}
ALLOWED_PIN = {"digest", "tag", "version", "none"}


def metadata_files() -> list[Path]:
    paths: list[Path] = []
    for path in (ROOT / "mcp").rglob("*.metadata.json"):
        paths.append(path)
    for path in (ROOT / "mcp").rglob("metadata.json"):
        paths.append(path)
    return sorted(set(paths))


def main() -> int:
    files = metadata_files()
    if not files:
        print("OK: no MCP metadata files present")
        return 0

    errors: list[str] = []
    for path in files:
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
        except Exception as exc:  # noqa: BLE001
            errors.append(f"{path.relative_to(ROOT)}: invalid JSON: {exc}")
            continue

        tm = data.get("trust_matrix")
        rel = path.relative_to(ROOT)
        if not isinstance(tm, dict):
            errors.append(f"{rel}: missing trust_matrix block")
            continue

        missing = REQUIRED_TM_FIELDS - tm.keys()
        if missing:
            errors.append(f"{rel}: trust_matrix missing fields {sorted(missing)}")

        for boolean_field in ("mutation_capable", "requires_egress", "requires_credentials"):
            if boolean_field in tm and not isinstance(tm[boolean_field], bool):
                errors.append(f"{rel}: trust_matrix.{boolean_field} must be boolean")

        if tm.get("signed_release") not in ALLOWED_SIGNED:
            errors.append(
                f"{rel}: trust_matrix.signed_release must be one of {sorted(ALLOWED_SIGNED)}"
            )
        if tm.get("pin_strategy") not in ALLOWED_PIN:
            errors.append(
                f"{rel}: trust_matrix.pin_strategy must be one of {sorted(ALLOWED_PIN)}"
            )

    if errors:
        print("ERROR: MCP trust_matrix validation failed", file=sys.stderr)
        for err in errors:
            print(f"  - {err}", file=sys.stderr)
        return 1

    print(f"OK: validated trust_matrix on {len(files)} MCP reference files")
    return 0


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