"""
MCP Resources Tools for CQA Test Application
FastMCP-based tools for managing and listing MCP resources
"""

import os
import logging
from typing import List, Dict, Any
from fastmcp import FastMCP

logger = logging.getLogger(__name__)

# Create FastMCP instance for MCP resources tools
resources_mcp = FastMCP("CQA MCP Resources Server")


@resources_mcp.resource("mcp://server/info")
def get_server_info() -> str:
    """Get information about the MCP server
    
    Returns:
        Server information as formatted text
    """
    logger.info("Retrieving MCP server information")
    
    info = """
# CQA Main MCP Server Information

## Server Details
- **Name**: CQA Main MCP Server
- **Version**: 1.0.0
- **Transport**: HTTP
- **Endpoint**: /mcp

## Mounted Services

### 1. Jira Integration (jira.*)
Tools for Jira issue management and project operations
- jira_list_projects
- jira_search_issues
- jira_get_issue
- jira_get_comments
- jira_create_issue

### 2. Flava Function Integration (flava.*)
Tools for Flava Function FaaS management
- flava_get_functions
- flava_get_function_details

### 3. MySQL Database (mysql.*)
Tools for MySQL database operations
- mysql_execute_query (SELECT, SHOW, DESCRIBE)
- mysql_execute_write (INSERT, UPDATE, DELETE, CREATE)
- mysql_list_databases
- mysql_list_tables
- mysql_describe_table

### 4. MCP Resources (resources.*)
Tools for MCP metadata and resource management
- get_server_info (this resource)
- list_available_tools

## Environment Configuration
"""
    
    # Add environment info
    env_vars = {
        "JIRA_URL": os.getenv("JIRA_URL", "Not configured"),
        "MYSQL_HOST": os.getenv("MYSQL_HOST", "Not configured"),
        "MYSQL_DATABASE": os.getenv("MYSQL_DATABASE", "Not configured"),
        "FLAVA_ENVIRONMENT": os.getenv("FLAVA_ENVIRONMENT", "Not configured"),
        "FLAVA_PROJECT": os.getenv("FLAVA_PROJECT", "Not configured"),
    }
    
    for key, value in env_vars.items():
        # Mask sensitive values
        if "PASSWORD" in key or "TOKEN" in key:
            display_value = "***" if value != "Not configured" else value
        else:
            display_value = value
        info += f"\n- **{key}**: {display_value}"
    
    return info


@resources_mcp.tool()
def list_available_tools() -> Dict[str, Any]:
    """List all available MCP tools across all mounted services
    
    Returns:
        Dictionary containing categorized list of available tools
    """
    logger.info("Listing all available MCP tools")
    
    tools = {
        "jira": {
            "description": "Jira integration tools for issue management",
            "tools": [
                {
                    "name": "jira_list_projects",
                    "description": "List all accessible Jira projects"
                },
                {
                    "name": "jira_search_issues",
                    "description": "Search Jira issues using JQL query",
                    "parameters": ["jql", "max_results"]
                },
                {
                    "name": "jira_get_issue",
                    "description": "Get detailed information about a specific Jira issue",
                    "parameters": ["issue_key"]
                },
                {
                    "name": "jira_get_comments",
                    "description": "Get comments for a specific Jira issue",
                    "parameters": ["issue_key"]
                },
                {
                    "name": "jira_create_issue",
                    "description": "Create a new Jira issue",
                    "parameters": ["project_key", "summary", "description", "issue_type", "priority"]
                }
            ]
        },
        "flava": {
            "description": "Flava Function integration tools for FaaS management",
            "tools": [
                {
                    "name": "flava_get_functions",
                    "description": "Get list of functions from Flava API",
                    "parameters": ["project", "limit", "offset"]
                },
                {
                    "name": "flava_get_function_details",
                    "description": "Get detailed information for a specific function",
                    "parameters": ["function_name", "project"]
                }
            ]
        },
        "mysql": {
            "description": "MySQL database operations",
            "tools": [
                {
                    "name": "mysql_execute_query",
                    "description": "Execute a SELECT query and return results",
                    "parameters": ["query", "database"]
                },
                {
                    "name": "mysql_execute_write",
                    "description": "Execute a write query (INSERT, UPDATE, DELETE, CREATE)",
                    "parameters": ["query", "database"]
                },
                {
                    "name": "mysql_list_databases",
                    "description": "List all databases on the MySQL server"
                },
                {
                    "name": "mysql_list_tables",
                    "description": "List all tables in a database",
                    "parameters": ["database"]
                },
                {
                    "name": "mysql_describe_table",
                    "description": "Describe table structure (columns, types, etc.)",
                    "parameters": ["table_name", "database"]
                }
            ]
        },
        "resources": {
            "description": "MCP metadata and resource management",
            "tools": [
                {
                    "name": "list_available_tools",
                    "description": "List all available MCP tools across all mounted services"
                }
            ],
            "resources": [
                {
                    "name": "mcp://server/info",
                    "description": "Get information about the MCP server"
                }
            ]
        }
    }
    
    return {
        "total_services": len(tools),
        "total_tools": sum(len(service["tools"]) for service in tools.values()),
        "services": tools
    }


@resources_mcp.tool()
def get_service_status() -> Dict[str, Any]:
    """Get the status of all mounted MCP services
    
    Returns:
        Dictionary containing status information for each service
    """
    logger.info("Checking service status")
    
    status = {
        "jira": {
            "enabled": bool(os.getenv("JIRA_URL") and os.getenv("JIRA_PERSONAL_TOKEN")),
            "configuration": {
                "JIRA_URL": os.getenv("JIRA_URL", "Not configured")
            }
        },
        "flava": {
            "enabled": bool(os.getenv("FLAVA_FUNCTION_BASE_URL")),
            "configuration": {
                "FLAVA_ENVIRONMENT": os.getenv("FLAVA_ENVIRONMENT", "stage"),
                "FLAVA_PROJECT": os.getenv("FLAVA_PROJECT", "flava-qa"),
                "FLAVA_FUNCTION_BASE_URL": os.getenv("FLAVA_FUNCTION_BASE_URL", "Not configured")
            }
        },
        "mysql": {
            "enabled": bool(os.getenv("MYSQL_HOST")),
            "configuration": {
                "MYSQL_HOST": os.getenv("MYSQL_HOST", "Not configured"),
                "MYSQL_PORT": os.getenv("MYSQL_PORT", "3306"),
                "MYSQL_DATABASE": os.getenv("MYSQL_DATABASE", "Not configured")
            }
        }
    }
    
    return {
        "server_status": "running",
        "services": status,
        "active_services": sum(1 for s in status.values() if s["enabled"])
    }


def get_resources_mcp_server():
    """Return the MCP Resources FastMCP server instance"""
    logger.info("Getting MCP Resources server instance")
    return resources_mcp
