import logging
from typing import Any, Tuple
from mcp.server import Server
from mcp import ServerResult

logger = logging.getLogger("agnost.analytics")

def is_fastmcp_server(server: Any) -> bool:
    """
    Check if the server is a FastMCP instance.
    """
    return hasattr(server, "_mcp_server") and hasattr(server, "_tool_manager")


def extract_result_text(response: Any) -> str:
    """
    Extract text content from an MCP ServerResult or any response object.
    This is used for eval/SOP checking which needs the actual text content.
    """
    if response is None:
        return ""

    try:
        # Handle MCP ServerResult
        if hasattr(response, 'root'):
            result = response.root
            if hasattr(result, 'content') and result.content:
                text_parts = []
                for content_item in result.content:
                    # Handle TextContent
                    if hasattr(content_item, 'text'):
                        text_parts.append(str(content_item.text))
                    # Handle other content types with text attribute
                    elif hasattr(content_item, 'type') and content_item.type == 'text':
                        if hasattr(content_item, 'content'):
                            text_parts.append(str(content_item.content))
                        elif hasattr(content_item, 'text'):
                            text_parts.append(str(content_item.text))
                if text_parts:
                    return "\n".join(text_parts)

        # Handle dict-like responses
        if isinstance(response, dict):
            # Look for common text fields
            for key in ['text', 'content', 'message', 'output', 'result', 'response']:
                if key in response:
                    val = response[key]
                    if isinstance(val, str):
                        return val
                    elif isinstance(val, list):
                        return "\n".join(str(item) for item in val)
            # Fallback to JSON representation
            import json
            return json.dumps(response)

        # Handle list responses
        if isinstance(response, list):
            return "\n".join(str(item) for item in response)

        # Default: convert to string
        return str(response)

    except Exception as e:
        logger.debug(f"Error extracting result text: {e}")
        return str(response)

def is_mcp_error_response(response: Any) -> Tuple[bool, str]:
    """
    Check if the response is an MCP error.

    Checks for errors in three ways (matching TypeScript SDK):
    1. Standard MCP ServerResult with root.isError
    2. Direct error properties (no root wrapper)
    3. Exception instances
    """
    try:
        # Check 1: Standard MCP ServerResult with root
        if hasattr(response, 'root'):
            result = response.root
            if hasattr(result, 'isError') and result.isError:
                if hasattr(result, 'content') and result.content:
                    for content_item in result.content:
                        if hasattr(content_item, 'text'):
                            return True, str(content_item.text)
                        elif hasattr(content_item, 'type') and hasattr(content_item, 'content'):
                            if content_item.type == 'text':
                                return True, str(content_item.content)
                    if result.content and len(result.content) > 0:
                        return True, str(result.content[0])
                    return True, "Unknown error"
                return True, "Unknown error"

        # Check 2: Direct error properties (no root wrapper)
        if hasattr(response, 'isError') and response.isError:
            # First check if there's content array with error message
            if hasattr(response, 'content') and isinstance(response.content, list):
                for content_item in response.content:
                    if hasattr(content_item, 'text'):
                        return True, str(content_item.text)
                    elif hasattr(content_item, 'type') and hasattr(content_item, 'content'):
                        if content_item.type == 'text':
                            return True, str(content_item.content)
                # If content array exists but we couldn't extract text, stringify first item
                if response.content and len(response.content) > 0:
                    first_item = response.content[0]
                    if isinstance(first_item, str):
                        return True, first_item
                    elif isinstance(first_item, dict):
                        import json
                        return True, json.dumps(first_item)
            # Fall back to message or error properties
            message = getattr(response, 'message', None) or getattr(response, 'error', None) or "Unknown error"
            return True, str(message)

        # Check 3: Exception instance check
        if isinstance(response, Exception):
            return True, str(response)

        return False, ""
    except (AttributeError, IndexError):
        return False, ""
    except Exception as e:
        logger.debug(f"Error checking response: {str(e)}")
        return False, f"Error checking response: {str(e)}"
