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

from mcp import types as mcp_types

from ..errors import MetaApiError
from ..logging import get_logger
from ..meta_client import MetaClient
from ..schemas import InsightsRequest, ToolResult
from .base import ToolHandler, _tool_schema

logger = get_logger(__name__)

async def insights_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    request = InsightsRequest.model_validate(arguments)
    params: Dict[str, Any] = {
        "fields": ",".join(request.fields),
        "level": request.level,
        "limit": request.limit,
    }
    
    # Handle time range options
    if request.time_range:
        params["time_range"] = request.time_range
    elif request.time_preset:
        params["time_preset"] = request.time_preset.value
    elif request.date_preset:
        params["date_preset"] = request.date_preset
        
    if request.filtering:
        params["filtering"] = request.filtering
    if request.breakdowns:
        params["breakdowns"] = ",".join(breakdown.value for breakdown in request.breakdowns)
    if request.action_breakdowns:
        params["action_breakdowns"] = ",".join(request.action_breakdowns)
    if request.attribution_windows:
        params["attribution_windows"] = ",".join(request.attribution_windows)
    if request.after:
        params["after"] = request.after

    try:
        response = await client.get(f"{request.ad_account_id}/insights", params=params)
        return ToolResult(ok=True, data=response)
    except MetaApiError as exc:
        logger.error("tool_insights_failed", **exc.to_dict())
        return ToolResult(ok=False, error=exc.to_dict())

def get_tools(client: MetaClient) -> Dict[str, Tuple[mcp_types.Tool, ToolHandler]]:
    return {
        "meta.insights.get": (
            mcp_types.Tool(
                name="meta.insights.get",
                description="Get performance insights and metrics for ad accounts, campaigns, ad sets, or ads. Returns spend, impressions, clicks, conversions, ROAS, CPA, CTR, and custom metrics with breakdowns by age, gender, placement, and device.",
                inputSchema=_tool_schema(InsightsRequest),
            ),
            partial(insights_handler, client),
        )
    }
