#!/usr/bin/env python3
"""Run Slither with a reviewed policy and fail explicitly on remaining findings."""
from __future__ import annotations

import json
import shutil
import subprocess
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
V3 = ROOT / "v3-src"
CONFIG = ROOT / "slither.config.json"


def main() -> None:
    slither = shutil.which("slither")
    if not slither:
        raise SystemExit("Slither is required for the release gate")
    if not shutil.which("forge"):
        raise SystemExit("Forge is required for Slither's Foundry compilation step")

    with tempfile.TemporaryDirectory(prefix="vaultfire-slither-") as directory:
        output = Path(directory) / "slither.json"
        completed = subprocess.run(
            [slither, ".", "--config-file", str(CONFIG), "--fail-none", "--json", str(output)],
            cwd=V3,
            text=True,
        )
        if completed.returncode != 0:
            raise SystemExit(f"Slither failed to execute (exit {completed.returncode})")
        if not output.exists():
            raise SystemExit("Slither did not emit machine-readable results")
        results = json.loads(output.read_text()).get("results", {}).get("detectors", [])

    if results:
        checks = ", ".join(sorted({item.get("check", "unknown") for item in results}))
        raise SystemExit(
            f"Slither release gate found {len(results)} non-baselined finding(s): {checks}. "
            "Do not suppress them with shell exit handling; review the config and finding."
        )
    print("verified Slither completed with zero non-baselined findings")


if __name__ == "__main__":
    main()
