#!/usr/bin/env python3
"""Verify an agent or skill — called by OpenClaw when the skill is invoked.

Usage (from OpenClaw):
    /operon-guard test path/to/agent.py
    /operon-guard scan path/to/agent.py
    /operon-guard verify path/to/skill/
"""

import json
import subprocess
import sys
from pathlib import Path


def run(command: str) -> str:
    """Entry point for OpenClaw skill invocation.

    Args:
        command: The user's input, e.g. "test my_agent.py" or "scan ./my-skill/"
    """
    parts = command.strip().split(None, 1)
    if not parts:
        return _usage()

    action = parts[0].lower()
    target = parts[1] if len(parts) > 1 else ""

    if action == "test":
        return _run_guard("test", target)
    elif action == "scan":
        return _run_guard("scan", target)
    elif action == "verify":
        return _run_guard("test", target)
    elif action == "init":
        return _run_guard("init", target)
    elif action in ("help", "--help", "-h"):
        return _usage()
    else:
        # assume the entire input is an agent path
        return _run_guard("test", command.strip())


def _run_guard(action: str, target: str) -> str:
    """Execute operon-guard CLI and return formatted output."""
    if not target:
        return "Error: Please specify an agent path or skill directory.\n\n" + _usage()

    target_path = Path(target).resolve()
    if not target_path.exists():
        return f"Error: '{target}' not found. Please check the path."

    # Use target dir itself as cwd if it's a directory, otherwise its parent
    work_dir = str(target_path) if target_path.is_dir() else str(target_path.parent)

    cmd = ["operon-guard", action]

    if action == "test":
        cmd.append(str(target_path))
        cmd.append("--json")  # structured output for OpenClaw
    elif action == "scan":
        cmd.append(str(target_path))
    elif action == "init":
        if target:
            cmd.extend(["--agent", str(target_path)])
        cmd.append("guardfile.yaml")  # explicit output filename

    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=120,
            cwd=work_dir,
        )

        output = result.stdout.strip()

        if action == "test" and result.returncode == 0:
            # parse JSON and format nicely
            try:
                data = json.loads(output)
                return _format_result(data)
            except json.JSONDecodeError:
                return output

        if result.returncode != 0:
            # test failed — agent didn't pass
            try:
                data = json.loads(output)
                return _format_result(data, failed=True)
            except (json.JSONDecodeError, ValueError):
                return f"Verification failed:\n{output}\n{result.stderr}"

        return output or result.stderr or "No output from operon-guard."

    except FileNotFoundError:
        return (
            "Error: operon-guard is not installed.\n"
            "Install it with: pip install operon-guard"
        )
    except subprocess.TimeoutExpired:
        return "Error: Verification timed out after 120 seconds."


def _format_result(data: dict, failed: bool = False) -> str:
    """Format JSON test results into a readable summary."""
    agent = data.get("agent", "unknown")
    score = data.get("score", 0)
    grade = data.get("grade", "?")
    passed = data.get("passed", False)
    duration = data.get("duration_ms", 0)

    status = "PASS" if passed else "FAIL"
    verdict = (
        "Safe to grant permissions."
        if passed
        else "DO NOT grant Write/Execute permissions until issues are resolved."
    )

    lines = [
        f"Agent: {agent}",
        f"Status: {status}",
        f"Trust Score: {score}/100 (Grade {grade})",
        f"Duration: {duration:.0f}ms",
        f"",
        f"Verdict: {verdict}",
        f"",
    ]

    checks = data.get("checks", {})
    if checks:
        lines.append("Check Results:")
        for name, check in checks.items():
            check_status = "PASS" if check.get("passed") else "FAIL"
            check_score = check.get("score", 0)
            lines.append(f"  {name}: {check_score}/100 ({check_status})")

            findings = check.get("findings", [])
            critical = [f for f in findings if f.get("severity") == "critical"]
            for f in critical[:3]:
                lines.append(f"    [CRITICAL] {f.get('message', '')}")

    return "\n".join(lines)


def _usage() -> str:
    return """Operon Guard — Agent Trust Verification

Commands:
  test <agent.py>     Full verification (determinism + safety + concurrency + latency)
  scan <agent.py>     Quick safety scan (injection + PII only)
  verify <skill/>     Verify an OpenClaw skill directory
  init <agent.py>     Generate a guardfile.yaml

Examples:
  /operon-guard test my_agent.py
  /operon-guard scan ./code-review-skill/
  /operon-guard verify ./my-custom-skill/"""


if __name__ == "__main__":
    if len(sys.argv) > 1:
        print(run(" ".join(sys.argv[1:])))
    else:
        print(_usage())
