"""
System connection test tool for the AGS SPARQL Agent.

This tool verifies that the MCP server is running and AGS agent can be initialized.
"""

import os
import sys

# Add src directory to path for imports
src_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
if src_dir not in sys.path:
    sys.path.insert(0, src_dir)

from ..base_tool import BaseToolMixin, handle_tool_errors, ToolError
from ...utils.agent_utils import get_agent


@handle_tool_errors
async def test_system_connection() -> str:
    """Test the MCP server connection and AGS agent status.
    
    This tool verifies that the MCP server is running, environment variables
    are configured, and the AGS agent can be initialized successfully.
    
    Returns:
        JSON response with connection status and environment details
    """
    try:
        # Reset agent to pick up any code changes  
        import ags_sparql_agent
        ags_sparql_agent.reset_agent()
        
        # Check environment variables that the real agent requires
        required_vars = ['ANZO_SERVER', 'ANZO_PORT', 'ANZO_USERNAME', 'ANZO_PASSWORD', 'GRAPHMART_URI', 'API_KEY']
        env_status = {}
        for var in required_vars:
            env_status[var] = "✅ Set" if os.getenv(var) else "❌ Missing"
        
        # Test agent initialization
        try:
            agent_test = await get_agent()
            agent_type = "✅ Real AGS Agent"
            agent_config = f"Server: {agent_test.config.ags_server}:{agent_test.config.ags_port}"
        except Exception as e:
            agent_type = f"❌ Agent Failed: {e}"
            agent_config = "Not available"
        
        return BaseToolMixin.create_success_response({
            "server": "AGS SPARQL Agent MCP Server",
            "agent_type": agent_type,
            "agent_config": agent_config,
            "environment": env_status
        }, "MCP server is running and responding")
        
    except Exception as e:
        return BaseToolMixin.create_error_response(
            str(e),
            suggestions=["Check environment variables", "Verify AGS server connectivity"]
        )