"""
OpenSoul MCP - Command Line Interface

Usage:
    opensoul-mcp install    Register as MCP server in Claude Code
    opensoul-mcp run        Start the MCP server (stdio mode)
    opensoul-mcp version    Show version
"""

import json
import os
import secrets
import sys
from pathlib import Path


def get_claude_settings_path():
    """Get Claude Code settings path."""
    return Path.home() / ".claude" / "settings.json"


def get_package_server_path():
    """Get the installed server.py path."""
    return str(Path(__file__).parent / "server.py")


def cmd_install():
    """Register OpenSoul as MCP server in Claude Code."""
    print("OpenSoul MCP Installer")
    print("=" * 40)

    # 1. Create config directory
    config_dir = Path.home() / ".opensoul"
    config_dir.mkdir(parents=True, exist_ok=True)
    data_dir = config_dir / "data"
    data_dir.mkdir(parents=True, exist_ok=True)

    config_file = config_dir / "config.json"
    if not config_file.exists():
        config = {
            "data_dir": str(data_dir),
            "vector_enabled": True,
            "ollama_url": "http://localhost:11434",
            "embedding_model": "bge-m3",
            "api_key": secrets.token_urlsafe(32),
        }
        with open(config_file, "w") as f:
            json.dump(config, f, indent=2)
        print(f"  Created config: {config_file}")
    else:
        print(f"  Config exists: {config_file}")

    # 2. Register MCP server
    settings_path = get_claude_settings_path()

    if settings_path.exists():
        with open(settings_path, "r") as f:
            settings = json.load(f)
    else:
        settings = {}

    if "mcpServers" not in settings:
        settings["mcpServers"] = {}

    # Find python executable
    python_path = sys.executable
    server_path = get_package_server_path()

    settings["mcpServers"]["opensoul"] = {
        "command": python_path,
        "args": [server_path],
    }

    settings_path.parent.mkdir(parents=True, exist_ok=True)
    with open(settings_path, "w") as f:
        json.dump(settings, f, indent=2)

    print(f"  Registered MCP server in: {settings_path}")
    print()
    print("Done! Next steps:")
    print("  1. Restart Claude Code")
    print('  2. Say: "Record a soul event about choosing between two options"')
    print("  3. Docs: https://opensoul.top")


def cmd_run():
    """Start the MCP server."""
    import asyncio
    from opensoul_mcp.server import main
    asyncio.run(main())


def cmd_version():
    """Show version."""
    from opensoul_mcp import __version__
    print(f"opensoul-mcp {__version__}")


def entry_point():
    """CLI entry point."""
    args = sys.argv[1:]

    if not args or args[0] in ("-h", "--help", "help"):
        print(__doc__.strip())
        return

    cmd = args[0]

    if cmd == "install":
        cmd_install()
    elif cmd == "run":
        cmd_run()
    elif cmd in ("version", "--version", "-V"):
        cmd_version()
    else:
        print(f"Unknown command: {cmd}")
        print(__doc__.strip())
        sys.exit(1)
