"""CLI entry point for mcp-diet."""

from __future__ import annotations

import sys

import click
from rich.console import Console

from mcp_diet.analyzer import DEFAULT_BUDGET, analyze_tools
from mcp_diet.client import get_tools_sse, get_tools_stdio
from mcp_diet.config import load_config
from mcp_diet.report import output_report
from mcp_diet.suggest import generate_suggestions, print_suggestions


@click.group()
@click.version_option(package_name="mcp-diet")
def cli():
    """mcp-diet: See how much context window your MCP tools consume."""


@cli.command()
@click.argument("server_cmd", nargs=-1, required=False)
@click.option("--sse", "sse_url", default=None, help="SSE server URL")
@click.option("--format", "fmt", type=click.Choice(["table", "json", "markdown"]), default="table", help="Output format")
@click.option("--budget", default=DEFAULT_BUDGET, type=int, help="Context budget in tokens")
def analyze(server_cmd: tuple[str, ...], sse_url: str | None, fmt: str, budget: int):
    """Analyze an MCP server's tool definitions.

    \b
    Examples:
      mcp-diet analyze -- npx @modelcontextprotocol/server-filesystem /tmp
      mcp-diet analyze --sse http://localhost:3000/sse
      mcp-diet analyze --format json -- python my_server.py
    """
    console = Console(stderr=True)

    try:
        if sse_url:
            console.print(f"Connecting to SSE server: {sse_url}")
            tools = get_tools_sse(sse_url)
            server_name = sse_url
        elif server_cmd:
            cmd_list = list(server_cmd)
            console.print(f"Starting server: {' '.join(cmd_list)}")
            tools = get_tools_stdio(cmd_list[0], cmd_list[1:])
            server_name = cmd_list[0]
        else:
            console.print("[red]Error: Provide a server command or --sse URL[/red]")
            sys.exit(1)
    except Exception as e:
        console.print(f"[red]Failed to connect: {e}[/red]")
        sys.exit(1)

    if not tools:
        console.print("[yellow]No tools found on this server.[/yellow]")
        sys.exit(0)

    summary = analyze_tools(tools, budget)
    output_report(summary, fmt, server_name)


@cli.command()
@click.option("--format", "fmt", type=click.Choice(["table", "json", "markdown"]), default="table", help="Output format")
@click.option("--budget", default=DEFAULT_BUDGET, type=int, help="Context budget in tokens")
def auto(fmt: str, budget: int):
    """Analyze all MCP servers from your Claude/MCP config.

    Reads .mcp.json (cwd) or ~/.claude/settings.json and analyzes each server.
    """
    console = Console(stderr=True)

    try:
        path, servers = load_config()
    except FileNotFoundError as e:
        console.print(f"[red]{e}[/red]")
        sys.exit(1)

    console.print(f"Config: {path}")
    console.print(f"Found {len(servers)} server(s)\n")

    all_tools = []
    for server in servers:
        console.print(f"Connecting to [cyan]{server.name}[/cyan]: {server.command} {' '.join(server.args)}")
        try:
            tools = get_tools_stdio(server.command, server.args)
            if tools:
                summary = analyze_tools(tools, budget)
                output_report(summary, fmt, server.name)
                all_tools.extend(tools)
            else:
                console.print(f"  [yellow]No tools found[/yellow]")
        except Exception as e:
            console.print(f"  [red]Failed: {e}[/red]")

    if len(all_tools) > 0 and len(servers) > 1:
        console.print("\n[bold]Combined Report (all servers):[/bold]\n")
        combined = analyze_tools(all_tools, budget)
        output_report(combined, fmt, "ALL SERVERS")


@cli.command()
@click.argument("server_cmd", nargs=-1, required=False)
@click.option("--sse", "sse_url", default=None, help="SSE server URL")
@click.option("--budget", default=DEFAULT_BUDGET, type=int, help="Context budget in tokens")
def suggest(server_cmd: tuple[str, ...], sse_url: str | None, budget: int):
    """Analyze and suggest optimizations for bloated tools.

    \b
    Examples:
      mcp-diet suggest -- npx @modelcontextprotocol/server-filesystem /tmp
      mcp-diet suggest --sse http://localhost:3000/sse
    """
    console = Console(stderr=True)

    try:
        if sse_url:
            console.print(f"Connecting to SSE server: {sse_url}")
            tools = get_tools_sse(sse_url)
            server_name = sse_url
        elif server_cmd:
            cmd_list = list(server_cmd)
            console.print(f"Starting server: {' '.join(cmd_list)}")
            tools = get_tools_stdio(cmd_list[0], cmd_list[1:])
            server_name = cmd_list[0]
        else:
            console.print("[red]Error: Provide a server command or --sse URL[/red]")
            sys.exit(1)
    except Exception as e:
        console.print(f"[red]Failed to connect: {e}[/red]")
        sys.exit(1)

    if not tools:
        console.print("[yellow]No tools found on this server.[/yellow]")
        sys.exit(0)

    summary = analyze_tools(tools, budget)
    output_report(summary, server_name=server_name)

    suggestions = generate_suggestions(summary)
    print_suggestions(suggestions)
