from typing import Any, Dict, Tuple
from functools import partial

from mcp import types as mcp_types

from ..logging import get_logger
from ..meta_client import MetaClient
from ..schemas import (
    ShareOfVoiceRequest,
    ToolResult
)
from .base import ToolHandler, _tool_schema

logger = get_logger(__name__)

async def competitive_share_of_voice_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    request = ShareOfVoiceRequest.model_validate(arguments)
    try:
        from ..competitive_tools import get_competitive_engine
        engine = get_competitive_engine()
        
        data = await engine.estimate_share_of_voice(request)
        
        return ToolResult(ok=True, data=data)
    except Exception as exc:
        logger.error("tool_competitive_share_of_voice_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

def get_tools(client: MetaClient) -> Dict[str, Tuple[mcp_types.Tool, ToolHandler]]:
    return {
        "meta.competitive.share_of_voice": (
            mcp_types.Tool(
                name="meta.competitive.share_of_voice",
                description="Estimate share of voice against competitors in your vertical. Track impression share and competitive positioning. Use for competitive intelligence.",
                inputSchema=_tool_schema(ShareOfVoiceRequest),
            ),
            partial(competitive_share_of_voice_handler, client),
        ),
    }
