"""Delimit MCP Server — run directly with Python.

Usage:
    python -m delimit.server

This starts the Delimit MCP server with 115 governance tools.
Configure your AI assistant to use this as an MCP server.
"""

import os
import sys
import subprocess
from pathlib import Path


def find_gateway():
    """Find the Delimit gateway installation."""
    candidates = [
        Path.home() / ".delimit" / "gateway",
        Path.home() / ".delimit_suite" / "gateway",
        Path(__file__).parent / "gateway",
    ]
    
    # Check DELIMIT_GATEWAY_ROOT env var
    env_root = os.environ.get("DELIMIT_GATEWAY_ROOT")
    if env_root:
        candidates.insert(0, Path(env_root))
    
    for path in candidates:
        server_py = path / "ai" / "server.py"
        if server_py.exists():
            return server_py
    
    return None


def main():
    """Start the MCP server."""
    server = find_gateway()
    
    if server is None:
        print("Delimit gateway not found. Install with:")
        print("  npx delimit-cli setup")
        print()
        print("Or set DELIMIT_GATEWAY_ROOT to the gateway directory.")
        sys.exit(1)
    
    # Find Python executable
    venv_py = Path.home() / ".delimit" / "venv" / "bin" / "python"
    venv_py2 = Path.home() / ".delimit_suite" / "venv" / "bin" / "python"
    
    if venv_py.exists():
        python = str(venv_py)
    elif venv_py2.exists():
        python = str(venv_py2)
    else:
        python = sys.executable
    
    os.execv(python, [python, str(server)])


if __name__ == "__main__":
    main()
