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 launch_campaign_war_room_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..realtime_intelligence import RealTimeIntelligenceEngine
        engine = RealTimeIntelligenceEngine(client)
        return await engine.launch_campaign_war_room(arguments)
    except Exception as exc:
        logger.error("tool_launch_campaign_war_room_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def monitor_competitive_intelligence_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..realtime_intelligence import RealTimeIntelligenceEngine
        engine = RealTimeIntelligenceEngine(client)
        return await engine.monitor_competitive_intelligence(arguments)
    except Exception as exc:
        logger.error("tool_monitor_competitive_intelligence_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def predict_performance_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..realtime_intelligence import RealTimeIntelligenceEngine
        engine = RealTimeIntelligenceEngine(client)
        return await engine.predict_performance(arguments)
    except Exception as exc:
        logger.error("tool_predict_performance_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def enable_autopilot_mode_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..realtime_intelligence import RealTimeIntelligenceEngine
        engine = RealTimeIntelligenceEngine(client)
        return await engine.enable_autopilot_mode(arguments)
    except Exception as exc:
        logger.error("tool_enable_autopilot_mode_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.realtime.launch_war_room": (
            mcp_types.Tool(
                name="meta.realtime.launch_war_room",
                description="Launch campaign war room for real-time monitoring. Get live dashboards with key metrics and alerts. Use for launch day monitoring.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(launch_campaign_war_room_handler, client),
        ),
        "meta.realtime.monitor_competition": (
            mcp_types.Tool(
                name="meta.realtime.monitor_competition",
                description="Monitor competitive intelligence in real-time. Track auction insights, CPM trends, and share of voice. Use for live competitive analysis.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(monitor_competitive_intelligence_handler, client),
        ),
        "meta.realtime.predict_performance": (
            mcp_types.Tool(
                name="meta.realtime.predict_performance",
                description="Predict next-hour performance using ML models. Forecast spend, conversions, and pacing. Use for proactive optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "campaign_id": {"type": "string"},
                        "prediction_horizon_hours": {"type": "integer"},
                    },
                    "required": ["campaign_id"],
                },
            ),
            partial(predict_performance_handler, client),
        ),
        "meta.realtime.enable_autopilot": (
            mcp_types.Tool(
                name="meta.realtime.enable_autopilot",
                description="Enable autopilot mode for autonomous optimization. Auto-adjust bids and budgets based on rules. Use for hands-off campaign management.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "campaign_id": {"type": "string"},
                        "mode": {"type": "string"},
                    },
                    "required": ["campaign_id"],
                },
            ),
            partial(enable_autopilot_mode_handler, client),
        ),
    }
