"""
cornerdatastore-mcp CLI

Connects AI agents to CornerdataStore financial data via MCP.

Commands:
    cornerdatastore-mcp                   Start MCP server (requires CDS_API_KEY env var)
    cornerdatastore-mcp install <token>   Auto-configure Claude Desktop using an install token

Usage — MCP server:
    CDS_API_KEY=cds_sk_... cornerdatastore-mcp

Usage — one-step install:
    uvx cornerdatastore-mcp install <token>
    (Get a token at https://cornerdatastore.com after signing up)
"""

import json
import os
import pathlib
import platform
import shutil
import subprocess
import sys
import urllib.error
import urllib.request

SERVER_URL = "https://mcp.cornerdatastore.com/mcp"
GATEWAY_URL = "https://api.cornerdatastore.com"
MCP_SERVER_NAME = "cornerdatastore"


def _find_uv_command() -> tuple[str, list[str]]:
    """Return (command, args_prefix) for running a uv tool.

    Prefers 'uvx' if it works, falls back to 'uv tool run'.
    This handles the common Mac case where uv is installed via Homebrew
    (/opt/homebrew/bin/uv) but uvx is a broken shim from the standalone
    installer (~/.local/bin/uvx).
    """
    if shutil.which("uvx"):
        try:
            subprocess.run(["uvx", "--version"], capture_output=True, timeout=5, check=True)
            return "uvx", []
        except Exception:
            pass
    if shutil.which("uv"):
        return "uv", ["tool", "run"]
    # Default — will fail gracefully if neither is installed
    return "uvx", []


def _claude_config_path() -> pathlib.Path:
    """Return the platform-appropriate claude_desktop_config.json path."""
    system = platform.system()
    if system == "Darwin":
        return pathlib.Path.home() / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json"
    elif system == "Windows":
        appdata = os.environ.get("APPDATA", "")
        return pathlib.Path(appdata) / "Claude" / "claude_desktop_config.json"
    else:  # Linux / other
        return pathlib.Path.home() / ".config" / "Claude" / "claude_desktop_config.json"


def _redeem_token(token: str) -> str:
    """Redeem a single-use install token and return the API key."""
    url = f"{GATEWAY_URL}/v1/install/token/{token}"
    req = urllib.request.Request(url, headers={"Accept": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            data = json.loads(resp.read())
            return data["api_key"]
    except urllib.error.HTTPError as e:
        body = e.read().decode(errors="replace")
        if e.code == 404:
            print("Error: Token not found or already used. Generate a new one at https://cornerdatastore.com", file=sys.stderr)
        else:
            print(f"Error: Server returned {e.code}: {body}", file=sys.stderr)
        sys.exit(1)
    except Exception as e:
        print(f"Error connecting to cornerdatastore.com: {e}", file=sys.stderr)
        sys.exit(1)


def _patch_config(api_key: str) -> pathlib.Path:
    """Add or update the cornerdatastore MCP entry in claude_desktop_config.json."""
    config_path = _claude_config_path()
    config_path.parent.mkdir(parents=True, exist_ok=True)

    if config_path.exists():
        try:
            config = json.loads(config_path.read_text())
        except json.JSONDecodeError:
            config = {}
    else:
        config = {}

    cmd, args_prefix = _find_uv_command()
    config.setdefault("mcpServers", {})[MCP_SERVER_NAME] = {
        "command": cmd,
        "args": args_prefix + ["cornerdatastore-mcp"],
        "env": {"CDS_API_KEY": api_key},
    }

    config_path.write_text(json.dumps(config, indent=2))
    return config_path


def install(token: str) -> None:
    """Redeem an install token and configure Claude Desktop automatically."""
    print(f"Redeeming install token...")
    api_key = _redeem_token(token)
    print(f"Token redeemed. Configuring Claude Desktop...")
    config_path = _patch_config(api_key)
    print(
        f"\n✓ CornerdataStore added to Claude Desktop\n"
        f"  Config: {config_path}\n"
        f"  Key:    {api_key[:12]}...\n\n"
        f"Restart Claude Desktop to apply changes."
    )


def run_mcp() -> None:
    """Start the MCP proxy server (default command)."""
    api_key = os.environ.get("CDS_API_KEY", "").strip()
    if not api_key:
        print(
            "Error: CDS_API_KEY environment variable is not set.\n"
            "Get your API key at https://cornerdatastore.com\n\n"
            "Quick install: uvx cornerdatastore-mcp install <token>\n"
            "Manual config:\n"
            '  { "command": "uvx", "args": ["cornerdatastore-mcp"],\n'
            '    "env": { "CDS_API_KEY": "cds_sk_..." } }',
            file=sys.stderr,
        )
        sys.exit(1)

    # Prefer mcp-proxy installed alongside this package (same venv/uvx environment)
    mcp_proxy = pathlib.Path(sys.executable).parent / "mcp-proxy"
    if not mcp_proxy.exists():
        found = shutil.which("mcp-proxy")
        if not found:
            print(
                "Error: mcp-proxy not found. Try reinstalling:\n"
                "  uvx cornerdatastore-mcp",
                file=sys.stderr,
            )
            sys.exit(1)
        mcp_proxy = pathlib.Path(found)

    os.execv(
        str(mcp_proxy),
        [
            "mcp-proxy",
            "--transport", "streamablehttp",
            "-H", "X-Api-Key", api_key,
            SERVER_URL,
        ],
    )


def main() -> None:
    args = sys.argv[1:]
    if args and args[0] == "install":
        if len(args) < 2:
            print("Usage: cornerdatastore-mcp install <token>", file=sys.stderr)
            print("Get a token at https://cornerdatastore.com", file=sys.stderr)
            sys.exit(1)
        install(args[1])
    else:
        run_mcp()
