#!/usr/bin/env python3
"""Fail closed on stale Base-pilot partner documents.

The discoverable surface is deliberately small and auditable: three root
partner/status/results documents plus every regular Markdown file below docs/.
Symlinks and paths escaping the rehearsal package are rejected.
"""
from __future__ import annotations

import argparse
import json
from pathlib import Path

try:
    from canonical_json import load_json_file
except ModuleNotFoundError:
    import importlib.util
    _canon_spec = importlib.util.spec_from_file_location("vaultfire_canonical_json", Path(__file__).with_name("canonical_json.py"))
    assert _canon_spec and _canon_spec.loader
    _canon = importlib.util.module_from_spec(_canon_spec); _canon_spec.loader.exec_module(_canon)
    load_json_file = _canon.load_json_file

FORBIDDEN = (
    "ForceExit(", "SlashV3", "getStakedAmount", "partnershipQualityScore",
    "loyaltyMultiplier", "globalFlourishingScore", "Flourishing Metric oracle",
)
ROOT_DOCUMENTS = ("README.md", "PREDEPLOYMENT_STATUS.md", "VALIDATION_RESULTS.md")


def candidate_marker(manifest: dict) -> str:
    candidate = manifest.get("candidate", {})
    commit = candidate.get("sourceCommit")
    return commit if isinstance(commit, str) else "BLOCKED_NO_FINAL_SOURCE_COMMIT"


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


def document_paths(package_root: Path) -> list[Path]:
    """Inspect every Markdown file and fail closed on unexpected locations."""
    root = package_root.resolve()
    docs = package_root / "docs"
    candidates = [package_root / name for name in ROOT_DOCUMENTS]
    if not docs.is_dir() or docs.is_symlink() or not _inside(root, docs):
        raise ValueError("docs must be a regular directory inside the rehearsal package")
    every_markdown = list(package_root.rglob("*.md"))
    for path in every_markdown:
        if path.parent == package_root and path.name not in ROOT_DOCUMENTS:
            raise ValueError(f"unexpected root partner Markdown document: {path.name}")
        if path.parent != package_root and docs not in path.parents:
            raise ValueError(f"unexpected partner Markdown location: {path}")
    candidates.extend(docs.rglob("*.md"))
    if not candidates:
        raise ValueError("no partner-facing documents found")
    result: list[Path] = []
    for path in candidates:
        if path.is_symlink() or not path.is_file() or not _inside(root, path):
            raise ValueError(f"partner-facing document must be a regular in-package file: {path}")
        result.append(path)
    return sorted(set(result))


def check(path: Path, marker: str) -> list[str]:
    text = path.read_text(encoding="utf-8")
    errors: list[str] = []
    if f"Candidate-Commit: `{marker}`" not in text:
        errors.append(f"{path}: missing exact Candidate-Commit metadata from canonical manifest")
    for token in FORBIDDEN:
        if token in text:
            errors.append(f"{path}: forbidden stale/disabled reference {token!r}")
    return errors


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--manifest", type=Path, required=True)
    parser.add_argument("--package-root", type=Path)
    parser.add_argument("paths", nargs="*", type=Path)
    args = parser.parse_args()
    manifest = load_json_file(args.manifest, "candidate manifest")
    root = args.package_root or args.manifest.parent
    try:
        allowed = document_paths(root)
        allowed_resolved = {path.resolve() for path in allowed}
        paths = args.paths or allowed
        for path in paths:
            if path.is_symlink() or not path.is_file() or path.resolve() not in allowed_resolved:
                raise ValueError(f"requested document is outside canonical partner-document discovery: {path}")
    except ValueError as exc:
        print(exc)
        return 1
    errors = [error for path in paths for error in check(path, candidate_marker(manifest))]
    for error in errors:
        print(error)
    return 1 if errors else 0


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