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

async def build_dynamic_product_sets_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..catalog_mastery import CatalogMasteryEngine
        engine = CatalogMasteryEngine(client)
        return await engine.build_dynamic_product_sets(arguments)
    except Exception as exc:
        logger.error("tool_build_dynamic_product_sets_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def optimize_product_feed_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..catalog_mastery import CatalogMasteryEngine
        engine = CatalogMasteryEngine(client)
        return await engine.optimize_product_feed(arguments)
    except Exception as exc:
        logger.error("tool_optimize_product_feed_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def analyze_catalog_performance_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..catalog_mastery import CatalogMasteryEngine
        engine = CatalogMasteryEngine(client)
        return await engine.analyze_catalog_performance(arguments)
    except Exception as exc:
        logger.error("tool_analyze_catalog_performance_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def setup_abandoned_cart_recovery_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..catalog_mastery import CatalogMasteryEngine
        engine = CatalogMasteryEngine(client)
        return await engine.setup_abandoned_cart_recovery(arguments)
    except Exception as exc:
        logger.error("tool_setup_abandoned_cart_recovery_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def automate_dynamic_retargeting_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..catalog_mastery import CatalogMasteryEngine
        engine = CatalogMasteryEngine(client)
        return await engine.automate_dynamic_retargeting(arguments)
    except Exception as exc:
        logger.error("tool_automate_dynamic_retargeting_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def monitor_catalog_health_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..catalog_mastery import CatalogMasteryEngine
        engine = CatalogMasteryEngine(client)
        return await engine.monitor_catalog_health(arguments)
    except Exception as exc:
        logger.error("tool_monitor_catalog_health_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def generate_cross_sell_recommendations_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..catalog_mastery import CatalogMasteryEngine
        engine = CatalogMasteryEngine(client)
        return await engine.generate_cross_sell_recommendations(arguments)
    except Exception as exc:
        logger.error("tool_generate_cross_sell_recommendations_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.catalog.sync": (
            mcp_types.Tool(
                name="meta.catalog.sync",
                description="Intelligent catalog sync with product feed. Handles inventory updates, price changes, and availability. Use for ecommerce catalog management.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "catalog_id": {"type": "string"},
                        "source_type": {"type": "string"},
                    },
                    "required": ["catalog_id"],
                },
            ),
            partial(sync_catalog_intelligently_handler, client),
        ),
        "meta.catalog.build_product_sets": (
            mcp_types.Tool(
                name="meta.catalog.build_product_sets",
                description="Build dynamic product sets with filter rules. Create segments by category, price, or custom attributes. Use for targeted dynamic ads.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "catalog_id": {"type": "string"},
                        "rules": {"type": "array"},
                    },
                    "required": ["catalog_id"],
                },
            ),
            partial(build_dynamic_product_sets_handler, client),
        ),
        "meta.catalog.optimize_feed": (
            mcp_types.Tool(
                name="meta.catalog.optimize_feed",
                description="Optimize product feed for better ad performance. Improve titles, descriptions, and images. Use for DPA and shopping ads optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "catalog_id": {"type": "string"},
                        "optimization_type": {"type": "string"},
                    },
                    "required": ["catalog_id"],
                },
            ),
            partial(optimize_product_feed_handler, client),
        ),
        "meta.catalog.analyze_performance": (
            mcp_types.Tool(
                name="meta.catalog.analyze_performance",
                description="Analyze catalog performance metrics. View top/bottom products, ROAS by category, and conversion rates. Use for product-level optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "catalog_id": {"type": "string"},
                    },
                    "required": ["catalog_id"],
                },
            ),
            partial(analyze_catalog_performance_handler, client),
        ),
        "meta.catalog.setup_abandoned_cart": (
            mcp_types.Tool(
                name="meta.catalog.setup_abandoned_cart",
                description="Setup abandoned cart recovery campaigns. Automate retargeting for cart abandoners. Use for ecommerce revenue recovery.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "catalog_id": {"type": "string"},
                        "pixel_id": {"type": "string"},
                        "ad_account_id": {"type": "string"},
                    },
                    "required": ["catalog_id", "ad_account_id"],
                },
            ),
            partial(setup_abandoned_cart_recovery_handler, client),
        ),
        "meta.catalog.automate_retargeting": (
            mcp_types.Tool(
                name="meta.catalog.automate_retargeting",
                description="Automate dynamic retargeting with product catalog. Shows viewed/carted products to previous visitors. Use for DPA retargeting automation.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "catalog_id": {"type": "string"},
                        "ad_account_id": {"type": "string"},
                    },
                    "required": ["catalog_id", "ad_account_id"],
                },
            ),
            partial(automate_dynamic_retargeting_handler, client),
        ),
        "meta.catalog.monitor_health": (
            mcp_types.Tool(
                name="meta.catalog.monitor_health",
                description="Monitor catalog health and data quality. Detect missing fields, errors, and sync issues. Use for feed troubleshooting.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "catalog_id": {"type": "string"},
                    },
                    "required": ["catalog_id"],
                },
            ),
            partial(monitor_catalog_health_handler, client),
        ),
        "meta.catalog.cross_sell_recommendations": (
            mcp_types.Tool(
                name="meta.catalog.cross_sell_recommendations",
                description="Generate cross-sell product recommendations using purchase patterns. Find complementary products. Use for upsell and AOV optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "catalog_id": {"type": "string"},
                        "base_product_id": {"type": "string"},
                    },
                    "required": ["catalog_id"],
                },
            ),
            partial(generate_cross_sell_recommendations_handler, client),
        ),
    }
