"""stobo mcp — install/uninstall MCP server for Claude Desktop."""

from __future__ import annotations

import json
import platform
import sys
from pathlib import Path
from shutil import which

import typer
from rich.console import Console

from stobo import config

app = typer.Typer(help="Manage the Stobo MCP server for Claude Desktop.")
console = Console()


def _claude_desktop_config_path() -> Path:
    """Return the Claude Desktop config path for the current OS."""
    system = platform.system()
    if system == "Darwin":
        return Path.home() / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json"
    elif system == "Windows":
        return Path.home() / "AppData" / "Roaming" / "Claude" / "claude_desktop_config.json"
    else:  # Linux
        return Path.home() / ".config" / "Claude" / "claude_desktop_config.json"


def _find_stobo_mcp() -> str | None:
    """Find the stobo-mcp binary path."""
    return which("stobo-mcp")


@app.command()
def install(
    api_key: str = typer.Option(None, "--api-key", "-k", help="Stobo API key (or uses saved key)"),
) -> None:
    """Install Stobo MCP server into Claude Desktop."""
    # Resolve API key: flag > saved config > empty (free tools still work)
    key = api_key or config.get_api_key() or ""

    # Find stobo-mcp binary
    mcp_bin = _find_stobo_mcp()
    if not mcp_bin:
        console.print("[red]stobo-mcp not found.[/] Install it with: [bold]pip install stobo-mcp[/]")
        raise typer.Exit(1)

    config_path = _claude_desktop_config_path()
    config_path.parent.mkdir(parents=True, exist_ok=True)

    # Load existing config or start fresh
    if config_path.exists():
        data = json.loads(config_path.read_text())
    else:
        data = {}

    env = {"STOBO_BASE_URL": "https://api.trystobo.com"}
    if key:
        env["STOBO_API_KEY"] = key

    data.setdefault("mcpServers", {})
    data["mcpServers"]["stobo"] = {"command": mcp_bin, "env": env}

    config_path.write_text(json.dumps(data, indent=2) + "\n")

    console.print("[green]\u2713[/] Stobo MCP server installed for Claude Desktop.")
    if key:
        console.print("  API key: [dim]configured[/]")
    else:
        console.print("  Free tools: [green]audit_site, audit_article, robots.txt, sitemap, freshness_code[/]")
        console.print("  [dim]Add an API key later with:[/] stobo mcp install --api-key sk_...")
    console.print()
    console.print("[yellow]Restart Claude Desktop[/] for the changes to take effect.")


@app.command()
def uninstall() -> None:
    """Remove Stobo MCP server from Claude Desktop."""
    config_path = _claude_desktop_config_path()
    if not config_path.exists():
        console.print("[yellow]No Claude Desktop config found.[/] Nothing to remove.")
        raise typer.Exit(0)

    data = json.loads(config_path.read_text())
    servers = data.get("mcpServers", {})

    if "stobo" not in servers:
        console.print("[yellow]Stobo MCP server not found in config.[/] Nothing to remove.")
        raise typer.Exit(0)

    del servers["stobo"]
    config_path.write_text(json.dumps(data, indent=2) + "\n")

    console.print("[green]\u2713[/] Stobo MCP server removed from Claude Desktop.")
    console.print("[yellow]Restart Claude Desktop[/] for the changes to take effect.")
