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 calculate_marginal_cpa_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..cost_efficiency_analysis import CostEfficiencyAnalysisEngine
        engine = CostEfficiencyAnalysisEngine(client)
        return await engine.calculate_marginal_cpa(arguments) # type: ignore
    except Exception as exc:
        logger.error("tool_calculate_marginal_cpa_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

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

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

async def analyze_auction_competitiveness_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..cost_efficiency_analysis import CostEfficiencyAnalysisEngine
        engine = CostEfficiencyAnalysisEngine(client)
        return await engine.analyze_auction_competitiveness(arguments) # type: ignore
    except Exception as exc:
        logger.error("tool_analyze_auction_competitiveness_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.cost_efficiency.calculate_marginal_cpa": (
            mcp_types.Tool(
                name="meta.cost_efficiency.calculate_marginal_cpa",
                description="Calculate marginal CPA to find the point of diminishing returns. Identify optimal spend level. Use for budget optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(calculate_marginal_cpa_handler, client),
        ),
        "meta.cost_efficiency.identify_waste": (
            mcp_types.Tool(
                name="meta.cost_efficiency.identify_waste",
                description="Identify wasted spend from non-converting placements, audiences, and creatives. Find budget leaks. Use for waste reduction.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(identify_wasted_spend_handler, client),
        ),
        "meta.cost_efficiency.diagnose_pacing": (
            mcp_types.Tool(
                name="meta.cost_efficiency.diagnose_pacing",
                description="Diagnose budget pacing issues like overspend, underspend, and irregular delivery. Fix delivery problems. Use for pacing troubleshooting.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(diagnose_budget_pacing_handler, client),
        ),
        "meta.cost_efficiency.analyze_auction": (
            mcp_types.Tool(
                name="meta.cost_efficiency.analyze_auction",
                description="Analyze auction competitiveness and bid position. Compare CPM to market rates. Use for auction intelligence.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(analyze_auction_competitiveness_handler, client),
        ),
    }
