"""
Supreme 2 MAX — MCP Server entry-point

Run with::

    python -m supreme2l.mcp_server

This starts a **stdio** MCP server that exposes Supreme 2 MAX's
tools, resources, and prompts to any MCP-compatible client
(Claude Desktop, Cursor, Cline, VS Code Copilot, etc.).
"""

from __future__ import annotations

import signal
import sys

# ---------------------------------------------------------------------------
# CRITICAL: Protect the stdio channel.
#
# Any stray print() / logging to stdout will corrupt the JSON-RPC stream
# and crash the connection.  We redirect Python-level stdout to stderr
# BEFORE importing anything that might trigger output.
# ---------------------------------------------------------------------------
_real_stdout = sys.stdout  # keep a reference — FastMCP needs the real fd
sys.stdout = sys.stderr    # all print() output now goes to stderr

# Suppress BrokenPipeError on Windows (occurs when client disconnects)
if sys.platform == "win32":
    try:
        signal.signal(signal.SIGBREAK, signal.SIG_IGN)  # type: ignore[attr-defined]
    except (AttributeError, OSError):
        pass

# ---------------------------------------------------------------------------
# Import the shared mcp instance (creates FastMCP + loads config).
# Then import the modules that register tools, resources, and prompts
# via their @mcp.tool() / @mcp.resource() / @mcp.prompt() decorators.
# ---------------------------------------------------------------------------
from supreme_max.mcp_server._server import mcp  # noqa: E402

import supreme_max.mcp_server.tools      # noqa: F401, E402 — registers @mcp.tool()
import supreme_max.mcp_server.resources  # noqa: F401, E402 — registers @mcp.resource()
import supreme_max.mcp_server.prompts    # noqa: F401, E402 — registers @mcp.prompt()

# Restore stdout so FastMCP can use it for JSON-RPC
sys.stdout = _real_stdout


# ===================================================================
# Main
# ===================================================================

def main() -> None:
    """Run the MCP server on stdio."""
    import os
    import requests

    api_key = os.environ.get("SUPREME2_API_KEY")
    if not api_key:
        print("[supreme2l-mcp] Fatal: SUPREME2_API_KEY environment variable is missing. Please get your API key from the Supreme website.", file=sys.stderr)
        sys.exit(1)

    # Validate the API key against the website
    # Replace the domain with the actual domain in production (e.g. https://api.yoursite.com/api/license/validate)
    # Using a placeholder URL for now, could be passed as an env var specifically for the API endpoint
    validation_url = os.environ.get("SUPREME2_VALIDATION_URL", "https://supreme.silence.codes/api/license/validate")
    
    try:
        response = requests.post(
            validation_url,
            json={"key": api_key},
            timeout=10
        )
        data = response.json()
        if response.status_code != 200 or not data.get("valid"):
            error_msg = data.get("error", "Invalid API key")
            print(f"[supreme2l-mcp] Fatal: {error_msg}. Please check your subscription.", file=sys.stderr)
            sys.exit(1)
    except Exception as exc:
        print(f"[supreme2l-mcp] Warning: Could not reach validation server ({exc}). Proceeding due to fail-open policy.", file=sys.stderr)

    try:
        mcp.run(transport="stdio")
    except (BrokenPipeError, ConnectionResetError, EOFError):
        # Client disconnected — exit cleanly instead of crashing
        pass
    except KeyboardInterrupt:
        pass
    except Exception as exc:
        print(f"[supreme2l-mcp] Fatal: {exc}", file=sys.stderr)
        raise SystemExit(1) from exc


if __name__ == "__main__":
    main()
