"""CLI for AgentCost — view cost summaries from the terminal."""

import argparse
import json
import os
import sys

import httpx

from .credentials import resolve_api_key, save as save_credentials, clear as clear_credentials, load as load_credentials


def main():
    parser = argparse.ArgumentParser(
        prog="agentcost",
        description="AgentCost CLI — track your AI agent costs",
    )
    parser.add_argument(
        "--api-key",
        default=None,
        help="Your AgentCost API key (overrides stored credentials).",
    )
    parser.add_argument(
        "--api-url",
        default="https://agentmeter.com/api/v1",
        help="API base URL",
    )

    subparsers = parser.add_subparsers(dest="command")

    # Login command
    subparsers.add_parser("login", help="Save your API key (one-time setup)")

    # Logout command
    subparsers.add_parser("logout", help="Remove stored credentials")

    # Status command
    subparsers.add_parser("status", help="Check login status and connection")

    # Run command — zero-code instrumentation
    run_parser = subparsers.add_parser(
        "run", help="Run a script with automatic cost tracking"
    )
    run_parser.add_argument(
        "--agent-id", default=None,
        help="Agent name for tracking (default: script filename)",
    )
    run_parser.add_argument(
        "script", help="Python script or module to run",
    )
    run_parser.add_argument(
        "script_args", nargs=argparse.REMAINDER,
        help="Arguments to pass to the script",
    )

    # Summary command
    summary_parser = subparsers.add_parser("summary", help="Show cost summary")
    summary_parser.add_argument(
        "--days", type=int, default=30, help="Number of days to look back"
    )

    # Agents command
    subparsers.add_parser("agents", help="List all agents")

    args = parser.parse_args()

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

    if args.command == "login":
        return cmd_login(args)
    if args.command == "logout":
        return cmd_logout()
    if args.command == "status":
        return cmd_status(args)
    if args.command == "run":
        return cmd_run(args)

    # All other commands need an API key
    api_key = resolve_api_key(args.api_key)
    if not api_key:
        print("Not logged in. Run: agentcost login")
        sys.exit(1)

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    }

    if args.command == "summary":
        response = httpx.get(
            f"{args.api_url}/costs/summary?days={args.days}",
            headers=headers,
            timeout=10.0,
        )

        if response.status_code != 200:
            print(f"Error: {response.text}")
            sys.exit(1)

        data = response.json()
        print_summary(data)

    elif args.command == "agents":
        response = httpx.get(
            f"{args.api_url}/agents",
            headers=headers,
            timeout=10.0,
        )

        if response.status_code != 200:
            print(f"Error: {response.text}")
            sys.exit(1)

        data = response.json()
        print_agents(data["agents"])


def cmd_login(args):
    """Interactive login — prompts for API key and stores it securely."""
    print()
    print("  AgentCost Login")
    print("  ───────────────")
    print()
    print("  Paste your API key from the AgentCost dashboard.")
    print("  (It starts with ac_)")
    print()

    api_key = input("  API key: ").strip()

    if not api_key:
        print("\n  No key entered. Aborting.")
        sys.exit(1)

    if not api_key.startswith("ac_"):
        print("\n  Warning: Key doesn't start with 'ac_'. Are you sure this is correct?")
        confirm = input("  Continue? (y/n): ").strip().lower()
        if confirm != "y":
            print("  Aborting.")
            sys.exit(1)

    # Verify the key works
    print("\n  Verifying...", end="", flush=True)
    try:
        response = httpx.get(
            f"{args.api_url}/pricing",
            headers={"Authorization": f"Bearer {api_key}"},
            timeout=10.0,
        )
        if response.status_code == 401:
            print(" invalid key.")
            print("  Check your key and try again.")
            sys.exit(1)
        print(" ok.")
    except httpx.RequestError:
        print(" could not reach server (saved anyway).")

    save_credentials(api_key, api_url=args.api_url)

    print()
    print("  Logged in! Credentials saved to ~/.config/agentcost/")
    print()
    print("  You're all set. Track any script with:")
    print("    agentcost run my_agent.py")
    print()


def cmd_logout():
    """Remove stored credentials."""
    if clear_credentials():
        print("Logged out. Credentials removed.")
    else:
        print("No stored credentials found.")


def cmd_status(args):
    """Show login status and verify connection."""
    api_key = resolve_api_key(args.api_key)

    print()
    if not api_key:
        print("  Status: not logged in")
        print("  Run: agentcost login")
        print()
        return

    masked = api_key[:6] + "..." + api_key[-4:]
    print(f"  Status: logged in")
    print(f"  Key:    {masked}")

    # Check connection
    try:
        response = httpx.get(
            f"{args.api_url}/pricing",
            headers={"Authorization": f"Bearer {api_key}"},
            timeout=10.0,
        )
        if response.status_code == 200:
            print(f"  Server: connected")
        elif response.status_code == 401:
            print(f"  Server: invalid key")
        else:
            print(f"  Server: error ({response.status_code})")
    except httpx.RequestError as e:
        print(f"  Server: unreachable")

    print()


def cmd_run(args):
    """Run a Python script with automatic cost tracking."""
    import runpy

    from . import init, shutdown

    script = args.script
    agent_id = args.agent_id or os.path.splitext(os.path.basename(script))[0]

    api_key = resolve_api_key(args.api_key)
    if not api_key:
        print("Not logged in. Run: agentcost login")
        sys.exit(1)

    # Patch sys.argv so the script sees its own args
    sys.argv = [script] + (args.script_args or [])

    init(api_key=api_key, agent_id=agent_id, api_url=args.api_url)
    print(f"[agentcost] Tracking '{agent_id}' — all LLM calls will be recorded.", file=sys.stderr)

    try:
        if script.endswith(".py"):
            runpy.run_path(script, run_name="__main__")
        else:
            runpy.run_module(script, run_name="__main__", alter_sys=True)
    except SystemExit:
        pass
    finally:
        shutdown()
        print(f"[agentcost] Done. Events flushed.", file=sys.stderr)


def print_summary(data: dict):
    """Print a formatted cost summary to the terminal."""
    change = data["cost_change_pct"]
    change_str = f"+{change}%" if change > 0 else f"{change}%"
    arrow = "↑" if change > 0 else "↓" if change < 0 else "→"

    print()
    print("┌─────────────────────────────────────────────┐")
    print("│          AgentMeter Cost Summary             │")
    print("├─────────────────────────────────────────────┤")
    print(f"│  Period: Last {data['period_days']} days{' ' * (29 - len(str(data['period_days'])))}│")
    print(f"│  Total Cost:     ${data['total_cost']:<25.4f}│")
    print(f"│  Total Events:   {data['total_events']:<26}│")
    print(f"│  vs. Previous:   {arrow} {change_str:<23}│")
    print("├─────────────────────────────────────────────┤")
    print("│  Top Agents                                 │")
    print("├─────────────────────────────────────────────┤")
    for agent in data.get("top_agents", []):
        name = agent["agent_id"][:20]
        cost = f"${agent['total_cost']:.4f}"
        padding = 42 - len(name) - len(cost)
        print(f"│  {name}{' ' * padding}{cost} │")
    print("├─────────────────────────────────────────────┤")
    print("│  Top Tools                                  │")
    print("├─────────────────────────────────────────────┤")
    for tool in data.get("top_tools", []):
        name = tool["component_name"][:20]
        cost = f"${tool['total_cost']:.4f}"
        padding = 42 - len(name) - len(cost)
        print(f"│  {name}{' ' * padding}{cost} │")
    print("└─────────────────────────────────────────────┘")
    print()


def print_agents(agents: list):
    """Print agent list to terminal."""
    print()
    print("┌─────────────────────────────────────────────────────────┐")
    print("│  Agent               │  Total Cost  │  Runs  │  Last   │")
    print("├─────────────────────────────────────────────────────────┤")
    for agent in agents:
        name = agent["agent_id"][:20].ljust(20)
        cost = f"${float(agent['total_cost_usd']):.2f}".rjust(11)
        runs = str(agent["total_runs"]).rjust(5)
        last = agent["last_seen"][:10] if agent["last_seen"] else "never"
        print(f"│  {name} │ {cost} │ {runs} │ {last} │")
    print("└─────────────────────────────────────────────────────────┘")
    print()


if __name__ == "__main__":
    main()
