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 ToolResult
from .base import ToolHandler

logger = get_logger(__name__)

async def create_whatsapp_campaign_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..multi_platform import MultiPlatformEngine
        engine = MultiPlatformEngine(client)
        return await engine.create_whatsapp_campaign(arguments)
    except Exception as exc:
        logger.error("tool_create_whatsapp_campaign_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def create_messenger_lead_campaign_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..multi_platform import MultiPlatformEngine
        engine = MultiPlatformEngine(client)
        return await engine.create_messenger_lead_campaign(arguments)
    except Exception as exc:
        logger.error("tool_create_messenger_lead_campaign_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def create_instagram_direct_campaign_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..multi_platform import MultiPlatformEngine
        engine = MultiPlatformEngine(client)
        return await engine.create_instagram_direct_campaign(arguments)
    except Exception as exc:
        logger.error("tool_create_instagram_direct_campaign_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def orchestrate_cross_platform_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..multi_platform import MultiPlatformEngine
        engine = MultiPlatformEngine(client)
        return await engine.orchestrate_cross_platform(arguments)
    except Exception as exc:
        logger.error("tool_orchestrate_cross_platform_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def create_multi_advertiser_campaign_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..multi_platform import MultiPlatformEngine
        engine = MultiPlatformEngine(client)
        return await engine.create_multi_advertiser_campaign(arguments)
    except Exception as exc:
        logger.error("tool_create_multi_advertiser_campaign_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def compare_platform_performance_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..multi_platform import MultiPlatformEngine
        engine = MultiPlatformEngine(client)
        return await engine.compare_platform_performance(arguments)
    except Exception as exc:
        logger.error("tool_compare_platform_performance_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.multi_platform.create_whatsapp": (
            mcp_types.Tool(
                name="meta.multi_platform.create_whatsapp",
                description="Create Click-to-WhatsApp campaigns that drive users to WhatsApp conversations. Generate leads via messaging. Use for WhatsApp advertising.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "campaign_name": {"type": "string"},
                        "whatsapp_number": {"type": "string"},
                        "message_template": {"type": "string"},
                    },
                    "required": ["ad_account_id", "whatsapp_number"],
                },
            ),
            partial(create_whatsapp_campaign_handler, client),
        ),
        "meta.multi_platform.create_messenger_lead": (
            mcp_types.Tool(
                name="meta.multi_platform.create_messenger_lead",
                description="Create Messenger lead generation campaigns with automated qualification flows. Capture leads via chat. Use for Messenger advertising.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "page_id": {"type": "string"},
                        "qualification_questions": {"type": "array"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(create_messenger_lead_campaign_handler, client),
        ),
        "meta.multi_platform.create_instagram_direct": (
            mcp_types.Tool(
                name="meta.multi_platform.create_instagram_direct",
                description="Create Instagram Direct campaigns driving users to DM conversations. Connect with audiences via Instagram chat. Use for Instagram messaging ads.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "instagram_actor_id": {"type": "string"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(create_instagram_direct_campaign_handler, client),
        ),
        "meta.multi_platform.orchestrate": (
            mcp_types.Tool(
                name="meta.multi_platform.orchestrate",
                description="Orchestrate messaging strategy across WhatsApp, Messenger, and Instagram. Allocate budget across platforms. Use for omnichannel messaging.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "platforms": {"type": "array"},
                        "total_budget": {"type": "number"},
                    },
                    "required": ["ad_account_id", "platforms"],
                },
            ),
            partial(orchestrate_cross_platform_handler, client),
        ),
        "meta.multi_platform.create_multi_advertiser": (
            mcp_types.Tool(
                name="meta.multi_platform.create_multi_advertiser",
                description="Create multi-advertiser partnership campaigns for co-branded advertising. Share creative with partner brands. Use for collaborative campaigns.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "partner_ids": {"type": "array"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(create_multi_advertiser_campaign_handler, client),
        ),
        "meta.multi_platform.compare_performance": (
            mcp_types.Tool(
                name="meta.multi_platform.compare_performance",
                description="Compare performance across Facebook, Instagram, Messenger, and WhatsApp. Analyze platform-level ROI. Use for cross-platform analysis.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "time_range": {"type": "object"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(compare_platform_performance_handler, client),
        ),
    }
