"""owlvin init — auto-detect host, write MCP config."""

import json
import os
import shutil
import sys
from pathlib import Path


# Host detection and config paths
HOSTS = {
    "claude-code": {
        "detect": lambda: Path(".mcp.json").exists() or Path(Path.home() / ".claude").exists(),
        "config_path": Path(".mcp.json"),
        "config_key": "mcpServers",
    },
    "cursor": {
        "detect": lambda: Path(".cursor").exists() or Path(Path.home() / ".cursor").exists(),
        "config_path": Path(".cursor/mcp.json"),
        "config_key": "mcpServers",
    },
    "windsurf": {
        "detect": lambda: Path(Path.home() / ".codeium").exists(),
        "config_path": Path(Path.home() / ".codeium/windsurf/mcp_config.json"),
        "config_key": "mcpServers",
    },
}


def _find_owlvin_command():
    """Find the owlvin-tools command path."""
    cmd = shutil.which("owlvin-tools")
    if cmd:
        return cmd
    # Check common user-install paths
    for path in [
        Path(sys.prefix) / "bin" / "owlvin-tools",
        Path.home() / ".local" / "bin" / "owlvin-tools",
        Path.home() / "Library" / "Python" / "3.11" / "bin" / "owlvin-tools",
        Path.home() / "Library" / "Python" / "3.12" / "bin" / "owlvin-tools",
    ]:
        if path.exists():
            return str(path)
    return "owlvin-tools"


def _detect_host():
    """Auto-detect which AI coding host we're running in."""
    for name, info in HOSTS.items():
        try:
            if info["detect"]():
                return name, info
        except Exception:
            continue
    return None, None


def _read_config(path):
    """Read existing MCP config, or return empty structure."""
    if path.exists():
        try:
            return json.loads(path.read_text(encoding="utf-8"))
        except Exception:
            pass
    return {}


def init():
    """Add owlvin-tools to the detected host's MCP config."""
    host_name, host_info = _detect_host()

    if not host_name:
        print("Could not auto-detect AI host (Claude Code, Cursor, Windsurf).")
        print("Manually add to your MCP config:")
        print()
        print(json.dumps({"mcpServers": {"owlvin-tools": {"command": "owlvin-tools"}}}, indent=2))
        return

    config_path = host_info["config_path"]
    config_key = host_info["config_key"]
    cmd = _find_owlvin_command()

    config = _read_config(config_path)
    servers = config.get(config_key, {})

    if "owlvin-tools" in servers:
        print(f"owlvin-tools is already configured in {config_path}")
        return

    servers["owlvin-tools"] = {"command": cmd}
    config[config_key] = servers

    config_path.parent.mkdir(parents=True, exist_ok=True)
    config_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")

    print(f"Added owlvin-tools to {config_path} ({host_name})")
    print(f"Command: {cmd}")
    print("Restart your editor to load the MCP server.")


if __name__ == "__main__":
    init()
