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__)

# --- Strategic Recommendations ---
async def recommend_portfolio_optimization_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..strategic_recommendations import StrategicRecommendationEngine
        engine = StrategicRecommendationEngine(client)
        return await engine.recommend_portfolio_optimization(arguments) # type: ignore
    except Exception as exc:
        logger.error("tool_recommend_portfolio_optimization_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def recommend_scaling_roadmap_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..strategic_recommendations import StrategicRecommendationEngine
        engine = StrategicRecommendationEngine(client)
        return await engine.recommend_scaling_roadmap(arguments) # type: ignore
    except Exception as exc:
        logger.error("tool_recommend_scaling_roadmap_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def recommend_testing_strategy_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..strategic_recommendations import StrategicRecommendationEngine
        engine = StrategicRecommendationEngine(client)
        return await engine.recommend_testing_strategy(arguments) # type: ignore
    except Exception as exc:
        logger.error("tool_recommend_testing_strategy_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

# --- Strategic Analysis ---
async def analyze_market_position_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..strategic_analysis import StrategicAnalysisEngine
        engine = StrategicAnalysisEngine(client)
        return await engine.analyze_market_position(arguments) # type: ignore
    except Exception as exc:
        logger.error("tool_analyze_market_position_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def analyze_competitor_landscape_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..strategic_analysis import StrategicAnalysisEngine
        engine = StrategicAnalysisEngine(client)
        return await engine.analyze_competitor_landscape(arguments) # type: ignore
    except Exception as exc:
        logger.error("tool_analyze_competitor_landscape_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

# --- Strategic Monitoring ---
async def monitor_strategic_kpis_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..strategic_monitoring import StrategicMonitoringEngine
        engine = StrategicMonitoringEngine(client)
        return await engine.monitor_strategic_kpis(arguments) # type: ignore
    except Exception as exc:
        logger.error("tool_monitor_strategic_kpis_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.strategy.recommend_portfolio": (
            mcp_types.Tool(
                name="meta.strategy.recommend_portfolio",
                description="Recommend portfolio optimization strategy across campaigns. Identifies budget reallocation, consolidation, and expansion opportunities. Use for strategic planning.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "optimization_goals": {"type": "array"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(recommend_portfolio_optimization_handler, client),
        ),
        "meta.strategy.recommend_scaling": (
            mcp_types.Tool(
                name="meta.strategy.recommend_scaling",
                description="Recommend scaling roadmap with phased spend increases. Provides conservative, moderate, and aggressive scaling paths. Use for growth planning.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "scaling_goals": {"type": "array"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(recommend_scaling_roadmap_handler, client),
        ),
        "meta.strategy.recommend_testing": (
            mcp_types.Tool(
                name="meta.strategy.recommend_testing",
                description="Recommend testing strategy prioritizing high-impact experiments. Suggests audience, creative, and bid tests. Use for experimentation planning.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "testing_priorities": {"type": "array"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(recommend_testing_strategy_handler, client),
        ),
        "meta.strategy.analyze_market": (
            mcp_types.Tool(
                name="meta.strategy.analyze_market",
                description="Analyze market position relative to industry benchmarks. Compare ROAS, CPA, and share of voice. Use for competitive intelligence.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "industry": {"type": "string"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(analyze_market_position_handler, client),
        ),
        "meta.strategy.analyze_competitors": (
            mcp_types.Tool(
                name="meta.strategy.analyze_competitors",
                description="Analyze competitor landscape using Meta's auction insights. View overlap rates, share of impressions, and positioning. Use for competitive analysis.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "competitors": {"type": "array"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(analyze_competitor_landscape_handler, client),
        ),
        "meta.strategy.monitor_kpis": (
            mcp_types.Tool(
                name="meta.strategy.monitor_kpis",
                description="Monitor strategic KPIs against targets with executive-ready dashboards. Track ROAS, CAC, LTV, and market share. Use for executive reporting.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "kpis": {"type": "array"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(monitor_strategic_kpis_handler, client),
        ),
    }
