"""
Agent Status CLI - Command line interface for Agent Status SDK.

Usage:
    agent-status status <agent_id>
    agent-status run <endpoint> [--prompts "Hello"]
    agent-status list
    agent-status register <endpoint> --name "My Agent"
"""

import argparse
import json
import os
import sys

import agent_status
from agent_status.client import AgentStatusError


def get_api_key() -> str:
    """Get API key from environment or prompt."""
    api_key = os.environ.get("RORA_API_KEY")
    if not api_key:
        print("Error: RORA_API_KEY environment variable not set", file=sys.stderr)
        print("Set it with: export RORA_API_KEY=your_api_key", file=sys.stderr)
        sys.exit(1)
    return api_key


def cmd_status(args):
    """Get agent status."""
    agent_status.init(api_key=get_api_key())
    try:
        status = agent_status.status(args.agent_id)
        print(f"Agent: {args.agent_id}")
        print(f"Verdict: {status.verdict.value}")
        print(f"Uptime (24h): {status.uptime_24h or 0}%")
        latency = f"{status.latency_p95} ms" if status.latency_p95 else "N/A"
        print(f"Latency P95: {latency}")
        pass_rate = f"{status.pass_rate:.1%}" if status.pass_rate is not None else "N/A"
        print(f"Pass Rate: {pass_rate}")
        if status.last_checked:
            print(f"Last Checked: {status.last_checked}")
    except AgentStatusError as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


def cmd_run(args):
    """Run one-off validation."""
    agent_status.init(api_key=get_api_key())
    prompts = args.prompts.split(",") if args.prompts else ["Hello, how are you?"]

    print(f"Running validation against: {args.endpoint}")
    print(f"Prompts: {prompts}")
    print("...")

    try:
        result = agent_status.run(
            endpoint=args.endpoint,
            prompts=prompts,
            max_nodes=args.nodes,
        )
        print(f"\nVerdict: {result.verdict.value}")
        print(f"Latency P50: {result.latency_p50}ms")
        print(f"Latency P95: {result.latency_p95}ms")
        print(f"Pass Rate: {result.pass_rate}")
        print(f"Probes: {result.successful_probes}/{result.total_probes} successful")

        if args.json:
            print("\nFull result:")
            print(json.dumps(result.model_dump(), indent=2, default=str))
    except AgentStatusError as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


def cmd_list(args):
    """List all agents."""
    agent_status.init(api_key=get_api_key())
    try:
        agents = agent_status.list_agents()
        if not agents:
            print("No agents registered.")
            return

        print(f"{'ID':<40} {'Name':<30} {'Status':<10} {'Last Status':<10}")
        print("-" * 90)
        for agent in agents:
            print(
                f"{agent.id:<40} {agent.name[:28]:<30} {agent.status:<10} {agent.last_status or 'N/A':<10}"
            )
    except AgentStatusError as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


def cmd_register(args):
    """Register a new agent."""
    agent_status.init(api_key=get_api_key())

    auth = None
    if args.token:
        auth = {"type": "bearer", "token": args.token}

    try:
        agent = agent_status.register(
            endpoint=args.endpoint,
            name=args.name,
            auth=auth,
            interval_minutes=args.interval,
        )
        print(f"Agent registered successfully!")
        print(f"ID: {agent.id}")
        print(f"Name: {agent.name}")
        print(f"Endpoint: {agent.endpoint_url}")
        print(f"Interval: {agent.interval_minutes} minutes")
    except AgentStatusError as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


def cmd_delete(args):
    """Delete an agent."""
    agent_status.init(api_key=get_api_key())
    try:
        agent_status.delete_agent(args.agent_id)
        print(f"Agent {args.agent_id} deleted.")
    except AgentStatusError as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


def main():
    parser = argparse.ArgumentParser(
        description="Agent Status CLI - Outside-in monitoring for AI agents",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument("--version", action="version", version=f"agent-status {agent_status.__version__}")

    subparsers = parser.add_subparsers(dest="command", help="Commands")

    # status command
    status_parser = subparsers.add_parser("status", help="Get agent status")
    status_parser.add_argument("agent_id", help="Agent UUID")
    status_parser.set_defaults(func=cmd_status)

    # run command
    run_parser = subparsers.add_parser("run", help="Run one-off validation")
    run_parser.add_argument("endpoint", help="Agent endpoint URL")
    run_parser.add_argument("--prompts", "-p", help="Comma-separated prompts")
    run_parser.add_argument("--nodes", "-n", type=int, default=3, help="Number of nodes")
    run_parser.add_argument("--json", "-j", action="store_true", help="Output full JSON")
    run_parser.set_defaults(func=cmd_run)

    # list command
    list_parser = subparsers.add_parser("list", help="List all agents")
    list_parser.set_defaults(func=cmd_list)

    # register command
    register_parser = subparsers.add_parser("register", help="Register a new agent")
    register_parser.add_argument("endpoint", help="Agent endpoint URL")
    register_parser.add_argument("--name", "-n", required=True, help="Agent name")
    register_parser.add_argument("--token", "-t", help="Bearer token for auth")
    register_parser.add_argument(
        "--interval", "-i", type=int, default=360, help="Probe interval in minutes"
    )
    register_parser.set_defaults(func=cmd_register)

    # delete command
    delete_parser = subparsers.add_parser("delete", help="Delete an agent")
    delete_parser.add_argument("agent_id", help="Agent UUID")
    delete_parser.set_defaults(func=cmd_delete)

    args = parser.parse_args()

    if not args.command:
        parser.print_help()
        sys.exit(1)

    args.func(args)


if __name__ == "__main__":
    main()
