"""
AgomTradePro MCP Server Test Script

Tests the MCP server functionality independently.
This script verifies that the MCP server can be initialized,
list tools, and execute tool calls.

Usage:
    python test_mcp_server.py

Requirements:
    - Django server running on http://localhost:8000
    - SDK installed in development mode
    - agomtradepro_mcp package available
"""

import json
import os
import sys
from pathlib import Path
from typing import Any

# Add project root and sdk directory to Python path
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))
sys.path.insert(0, str(project_root / "sdk"))

# Set environment variables for testing
os.environ["AGOMTRADEPRO_BASE_URL"] = "http://localhost:8000"
os.environ.setdefault("AGOMTRADEPRO_API_TOKEN", "test-token")


def print_section(title: str) -> None:
    """Print a formatted section header"""
    print("\n" + "=" * 60)
    print(f"  {title}")
    print("=" * 60)


def print_test(name: str) -> None:
    """Print a test name"""
    print(f"\n[{name}]")


def print_success(message: str) -> None:
    """Print a success message"""
    print(f"  OK: {message}")


def print_error(message: str) -> None:
    """Print an error message"""
    print(f"  FAIL: {message}", file=sys.stderr)


def print_info(message: str) -> None:
    """Print an info message"""
    print(f"  INFO: {message}")


def print_json(data: Any, indent: int = 2) -> None:
    """Print JSON data"""
    print(json.dumps(data, indent=indent, ensure_ascii=False))


def test_import_mcp() -> None:
    """Test 1: Import MCP Server"""
    print_test("Test 1: Import MCP Server")
    try:
        from agomtradepro_mcp import server  # noqa: F401
        print_success("MCP server module imported successfully")
    except ImportError as e:
        raise AssertionError(f"Failed to import MCP server: {e}. " "Make sure the SDK is installed: pip install -e sdk/") from e


def test_server_instance() -> None:
    """Test 2: Create Server Instance"""
    print_test("Test 2: Create Server Instance")
    try:
        from agomtradepro_mcp.server import server

        print_success(f"Server instance created: {server.name}")
    except Exception as e:
        raise AssertionError(f"Failed to create server instance: {e}") from e


def test_list_tools() -> None:
    """Test 3: List Available Tools"""
    print_test("Test 3: List Available Tools")
    try:
        import asyncio

        from agomtradepro_mcp.server import server

        tools = asyncio.run(server.list_tools())
        assert len(tools) > 0, "No MCP tools registered"

        print_success(f"Found {len(tools)} tools")
        print_info("The server provides tools for:")
        print_info("  - Regime: get_current_regime, calculate_regime, explain_regime")
        print_info("  - Signal: list_signals, check_signal_eligibility, create_signal")
        print_info("  - Data Center Macro: data_center_list_indicators, data_center_get_macro_series")
        print_info("  - Policy: get_policy_status, list_policy_events")
        print_info("  - Backtest: list_backtests, get_backtest_result")
        print_info("  - And more...")
    except Exception as e:
        raise AssertionError(f"Failed to list tools: {e}") from e


def test_list_resources() -> None:
    """Test 4: List Available Resources"""
    print_test("Test 4: List Available Resources")
    try:
        import asyncio

        from agomtradepro_mcp.server import list_resources

        resources = asyncio.run(list_resources())

        print_success(f"Found {len(resources)} resources")
        for resource in resources:
            print_info(f"  - {resource['uri']}: {resource['name']}")
    except Exception as e:
        raise AssertionError(f"Failed to list resources: {e}") from e


def test_read_resource() -> None:
    """Test 5: Read Resource Content"""
    print_test("Test 5: Read Resource Content")
    try:
        import asyncio

        from agomtradepro_mcp.server import read_resource

        # Read current regime resource
        content = asyncio.run(read_resource("agomtradepro://regime/current"))

        print_success("Resource content retrieved")
        print_info("Current regime resource:")
        print(f"  {content[:100]}...")
    except Exception as e:
        print_info(f"Read resource skipped due to runtime data issue: {e}")


def test_list_prompts() -> None:
    """Test 6: List Available Prompts"""
    print_test("Test 6: List Available Prompts")
    try:
        import asyncio

        from agomtradepro_mcp.server import list_prompts

        prompts = asyncio.run(list_prompts())

        print_success(f"Found {len(prompts)} prompts")
        for prompt in prompts:
            args_info = ""
            if prompt.get("arguments"):
                args_info = f" ({len(prompt['arguments'])} args)"
            print_info(f"  - {prompt['name']}{args_info}: {prompt['description']}")
    except Exception as e:
        raise AssertionError(f"Failed to list prompts: {e}") from e


def test_get_prompt() -> None:
    """Test 7: Get Prompt Content"""
    print_test("Test 7: Get Prompt Content")
    try:
        import asyncio

        from agomtradepro_mcp.server import get_prompt

        # Get analyze_macro_environment prompt
        prompt = asyncio.run(get_prompt("analyze_macro_environment"))

        print_success("Prompt content retrieved")
        print_info(f"Prompt length: {len(prompt)} characters")
    except Exception as e:
        raise AssertionError(f"Failed to get prompt: {e}") from e


def test_tool_imports() -> None:
    """Test 8: Test Tool Module Imports"""
    print_test("Test 8: Test Tool Module Imports")
    try:
        from agomtradepro_mcp.tools import (  # noqa: F401
            account_tools,
            ai_provider_tools,
            alpha_trigger_tools,
            asset_analysis_tools,
            audit_tools,
            backtest_tools,
            beta_gate_tools,
            dashboard_tools,
            data_center_tools,
            decision_rhythm_tools,
            equity_tools,
            events_tools,
            filter_tools,
            fund_tools,
            policy_tools,
            prompt_tools,
            realtime_tools,
            regime_tools,
            sector_tools,
            sentiment_tools,
            signal_tools,
            simulated_trading_tools,
            strategy_tools,
            task_monitor_tools,
        )

        print_success("All tool modules imported successfully")
        print_info("Available tool categories:")
        print_info("  - regime_tools")
        print_info("  - signal_tools")
        print_info("  - data_center_tools")
        print_info("  - policy_tools")
        print_info("  - backtest_tools")
        print_info("  - account_tools")
        print_info("  - simulated_trading_tools")
        print_info("  - equity_tools")
        print_info("  - fund_tools")
        print_info("  - sector_tools")
        print_info("  - strategy_tools")
        print_info("  - realtime_tools")
        print_info("  - ai_provider_tools")
        print_info("  - prompt_tools")
        print_info("  - audit_tools")
        print_info("  - events_tools")
        print_info("  - decision_rhythm_tools")
        print_info("  - beta_gate_tools")
        print_info("  - alpha_trigger_tools")
        print_info("  - dashboard_tools")
        print_info("  - asset_analysis_tools")
        print_info("  - sentiment_tools")
        print_info("  - task_monitor_tools")
        print_info("  - filter_tools")
    except ImportError as e:
        raise AssertionError(f"Failed to import tool modules: {e}") from e


def test_sdk_client_from_mcp() -> None:
    """Test 9: Test SDK Client from MCP Context"""
    print_test("Test 9: Test SDK Client from MCP Context")
    try:
        from agomtradepro import AgomTradeProClient

        client = AgomTradeProClient()

        # Test that we can access the API through the client
        # This simulates what the MCP server does
        try:
            regime = client.regime.get_current()
            print_success(f"SDK client working, current regime: {regime.dominant_regime}")
        except Exception:
            # Even if data is not available, the client should work
            print_success("SDK client initialized successfully")
    except Exception as e:
        raise AssertionError(f"Failed to create SDK client: {e}") from e


def main() -> int:
    """Run all tests"""
    print_section("AgomTradePro MCP Server Test")

    # Check if server is running
    print_test("Server Check")
    try:
        import requests
        requests.get("http://localhost:8000/api/", timeout=5)
        print_success("Server is running")
    except Exception as e:
        print_error(f"Cannot connect to server: {e}")
        print_info("Please start the server first: .\\scripts\\start-dev.ps1")
        return 1

    # Run tests
    tests = [
        ("Import MCP Server", test_import_mcp),
        ("Create Server Instance", test_server_instance),
        ("List Available Tools", test_list_tools),
        ("List Available Resources", test_list_resources),
        ("Read Resource Content", test_read_resource),
        ("List Available Prompts", test_list_prompts),
        ("Get Prompt Content", test_get_prompt),
        ("Test Tool Imports", test_tool_imports),
        ("SDK Client from MCP", test_sdk_client_from_mcp),
    ]

    results: list[tuple[str, bool]] = []

    for name, test_func in tests:
        try:
            test_func()
            results.append((name, True))
        except AssertionError as e:
            print_error(str(e))
            results.append((name, False))
        except Exception as e:
            print_error(f"Unexpected error: {e}")
            results.append((name, False))

    # Print summary
    print_section("Test Summary")

    passed = sum(1 for _, result in results if result)
    total = len(results)

    for name, result in results:
        status = "PASS" if result else "FAIL"
        symbol = "OK" if result else "X"
        print(f"  [{symbol}] {name}: {status}")

    print()
    print(f"  Total: {passed}/{total} tests passed")

    if passed == total:
        print_success("All tests passed!")
        print()
        print_info("To use the MCP server with Claude Code:")
        print_info("1. Add to ~/.config/claude-code/mcp_servers.json:")
        print_info('''
{
  "mcpServers": {
    "agomtradepro": {
      "command": "python",
      "args": ["-m", "agomtradepro_mcp.server"],
      "cwd": "D:/githv/agomTradePro/sdk",
      "env": {
        "AGOMTRADEPRO_BASE_URL": "http://localhost:8000"
      }
    }
  }
}''')
        return 0
    else:
        print_error(f"{total - passed} test(s) failed")
        return 1


if __name__ == "__main__":
    sys.exit(main())
