"""Pentest command -- simulate SAFE-MCP attack patterns against detectors."""

from __future__ import annotations

import argparse
import sys


def _pentest_print_report(report: dict) -> None:  # type: ignore[type-arg]
    """Pretty-print a pentest report to the terminal."""
    print("\n  Navil Pentest \u2014 SAFE-MCP Attack Simulation")
    print("  \u2550" * 51)
    print()
    print(f"  {'Scenario':<24} {'Verdict':<10} {'Alerts':<8} {'Severity'}")
    sep = "\u2500"
    print(f"  {sep * 24} {sep * 10} {sep * 8} {sep * 10}")

    for r in report.get("results", []):
        verdict = r.get("verdict", "?")
        mark = "\u2713" if verdict == "PASS" else "\u2717" if verdict == "FAIL" else "~"
        alerts_count = len(r.get("alerts_fired", []))
        severity = r.get("severity", "\u2014")
        print(f"  {r['scenario']:<24} {mark} {verdict:<8} {alerts_count:<8} {severity}")

    total = report.get("total_scenarios", 0)
    passed = report.get("passed", 0)
    rate = report.get("detection_rate", 0.0)
    print()
    print(f"  Detection Rate: {passed}/{total} ({rate}%)")
    print()


def _pentest_run(cli, args: argparse.Namespace) -> int:  # type: ignore[no-untyped-def]
    from navil.pentest import SCENARIOS, PentestEngine

    engine = PentestEngine(cli.anomaly_detector, cli.policy_engine)

    if args.scenario:
        if args.scenario not in SCENARIOS:
            print(
                f"Unknown scenario: {args.scenario}\nAvailable: {', '.join(SCENARIOS.keys())}",
                file=sys.stderr,
            )
            return 1
        result = engine.run_scenario(args.scenario)
        report = {
            "status": "completed",
            "total_scenarios": 1,
            "passed": 1 if result.verdict == "PASS" else 0,
            "failed": 1 if result.verdict == "FAIL" else 0,
            "partial": 1 if result.verdict == "PARTIAL" else 0,
            "detection_rate": 100.0 if result.verdict == "PASS" else 0.0,
            "results": [result.to_dict()],
        }
    else:
        report = engine.run_all()

    if args.json_output:
        import json as _json

        print(_json.dumps(report, indent=2))
    else:
        _pentest_print_report(report)

    if args.output:
        import json as _json

        with open(args.output, "w") as f:
            _json.dump(report, f, indent=2)
        print(f"\n  Report saved to {args.output}")

    return 0 if report["failed"] == 0 else 1


def register(subparsers: argparse._SubParsersAction, cli_class: type) -> None:
    """Register the pentest subcommand."""
    pentest_parser = subparsers.add_parser(
        "pentest", help="Simulate SAFE-MCP attack patterns against detectors"
    )
    pentest_parser.add_argument(
        "--scenario",
        default=None,
        help="Run a specific scenario (e.g., reconnaissance, persistence, c2_beaconing). "
        "Omit to run all 11 scenarios.",
    )
    pentest_parser.add_argument(
        "--json",
        action="store_true",
        dest="json_output",
        help="Output raw JSON instead of formatted table",
    )
    pentest_parser.add_argument("-o", "--output", default=None, help="Save JSON report to file")
    pentest_parser.set_defaults(func=_pentest_run)
