"""Entry point for running MCP server as module.

Usage:
    python -m cubesquare.mcp              # Run server (stdio)
    python -m cubesquare.mcp --list       # List all tools
    python -m cubesquare.mcp --test       # Run test suite
    python -m cubesquare.mcp --call TOOL  # Call a tool
"""

import sys
import os
import json

# ── Suppress C-level stdout pollution during import ──────────
# Some DLLs (Qt, etc.) print to C stdout via printf, bypassing
# Python's sys.stdout. This corrupts MCP JSON-RPC framing.
# We redirect fd 1 to devnull during import, then restore it.
_is_server_mode = len(sys.argv) < 2  # No args = stdio server mode

if _is_server_mode:
    _saved_stdout_fd = os.dup(1)
    _devnull_fd = os.open(os.devnull, os.O_WRONLY)
    os.dup2(_devnull_fd, 1)

from .server import MCPServer

if _is_server_mode:
    os.dup2(_saved_stdout_fd, 1)
    os.close(_devnull_fd)
    os.close(_saved_stdout_fd)


def print_tools(server: MCPServer):
    """Print all available tools."""
    tools = server.list_tools()
    print(f"\nCubesquare MCP Server - {len(tools)} Tools\n")
    print("=" * 60)

    # Group by category based on tool name patterns
    categories = {
        "Core": ["cst_shell", "c_performance_shell", "primitives_shell"],
        "Routing": ["i_logic_shell", "circular_shell", "predict_shell"],
        "Semantic": ["beehive_shell", "semantic_chain_shell", "language_shell"],
        "Physics": ["time_shell", "distance_shell", "mass_shell", "gravity_shell", "world_shell"],
        "Analysis": ["ecosystem_shell", "data_analysis_shell", "learning_shell"],
        "Basin": ["basin_system", "light_basin_shell", "meaning_shell"],
        "Agent": ["new_agent_shell", "unified_field_tools", "gene_shell"],
        "Manifold": ["manifold_shell", "sql_shell", "twelve_shell"],
        "Telemetry": ["telemetry_shell", "srl_shell"],
        "Consciousness": ["self_shell", "brain_shell", "thinking_shell"]
    }

    for category, tool_names in categories.items():
        category_tools = [t for t in tools if t["name"] in tool_names]
        if category_tools:
            print(f"\n{category}:")
            for tool in category_tools:
                print(f"  {tool['name']}")
                print(f"    {tool['description'][:70]}...")

    print("\n" + "=" * 60)
    print(f"Total: {len(tools)} tools")
    print("\nUsage: python -m cubesquare.mcp --call TOOL_NAME")


def test_tools(server: MCPServer):
    """Run quick test on key tools."""
    print("\nTesting Cubesquare MCP Tools\n")
    print("=" * 60)

    tests = [
        ("primitives_shell", {"command": "status"}),
        ("i_logic_shell", {"command": "multiply", "state1": "SPIRAL", "state2": "SPIRAL"}),
        ("srl_shell", {"command": "compute", "depth": 100}),
        ("cst_shell", {"command": "status"}),
    ]

    passed = 0
    for tool_name, args in tests:
        result = server.call_tool(tool_name, args)
        success = "error" not in result
        status = "PASS" if success else "FAIL"
        print(f"  {tool_name}: {status}")
        if success:
            passed += 1
        else:
            print(f"    Error: {result.get('error')}")

    print("\n" + "=" * 60)
    print(f"Passed: {passed}/{len(tests)}")


def call_tool(server: MCPServer, tool_name: str, args_json: str = "{}"):
    """Call a specific tool with arguments."""
    try:
        args = json.loads(args_json)
    except json.JSONDecodeError:
        print(f"Error: Invalid JSON arguments: {args_json}")
        sys.exit(1)

    result = server.call_tool(tool_name, args)
    print(json.dumps(result, indent=2))


def main():
    server = MCPServer()

    if len(sys.argv) < 2:
        # No args = run server
        server.run()
        return

    arg = sys.argv[1]

    if arg == "--list":
        print_tools(server)
    elif arg == "--test":
        test_tools(server)
    elif arg == "--call":
        if len(sys.argv) < 3:
            print("Usage: python -m cubesquare.mcp --call TOOL_NAME [ARGS_JSON]")
            sys.exit(1)
        tool_name = sys.argv[2]
        args_json = sys.argv[3] if len(sys.argv) > 3 else "{}"
        call_tool(server, tool_name, args_json)
    elif arg == "--help" or arg == "-h":
        print("""
Cubesquare MCP Server

Usage:
    python -m cubesquare.mcp              Run server (stdio transport)
    python -m cubesquare.mcp --list       List all tools
    python -m cubesquare.mcp --test       Run test suite
    python -m cubesquare.mcp --call TOOL [ARGS]   Call a tool

Examples:
    python -m cubesquare.mcp --call i_logic_shell '{"command":"multiply","state1":"SPIRAL","state2":"SPIRAL"}'
    python -m cubesquare.mcp --call primitives_shell '{"command":"status"}'
    python -m cubesquare.mcp --call beehive_shell '{"command":"status"}'
""")
    else:
        print(f"Unknown argument: {arg}")
        print("Use --help for usage information")
        sys.exit(1)


if __name__ == "__main__":
    main()
