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

async def create_virtual_tryon_campaign_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..ar_vr_ads import ARVRAdsEngine
        engine = ARVRAdsEngine(client)
        return await engine.create_virtual_tryon_campaign(arguments)
    except Exception as exc:
        logger.error("tool_create_virtual_tryon_campaign_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def create_3d_product_showcase_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..ar_vr_ads import ARVRAdsEngine
        engine = ARVRAdsEngine(client)
        return await engine.create_3d_product_showcase(arguments)
    except Exception as exc:
        logger.error("tool_create_3d_product_showcase_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def create_ar_shopping_experience_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..ar_vr_ads import ARVRAdsEngine
        engine = ARVRAdsEngine(client)
        return await engine.create_ar_shopping_experience(arguments)
    except Exception as exc:
        logger.error("tool_create_ar_shopping_experience_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def create_meta_horizon_ad_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..ar_vr_ads import ARVRAdsEngine
        engine = ARVRAdsEngine(client)
        return await engine.create_meta_horizon_ad(arguments)
    except Exception as exc:
        logger.error("tool_create_meta_horizon_ad_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def get_ar_performance_analytics_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..ar_vr_ads import ARVRAdsEngine
        engine = ARVRAdsEngine(client)
        return await engine.get_ar_performance_analytics(arguments)
    except Exception as exc:
        logger.error("tool_get_ar_performance_analytics_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.ar_vr.create_spark_ar": (
            mcp_types.Tool(
                name="meta.ar_vr.create_spark_ar",
                description="Create Spark AR effect ads with interactive filters and lenses. Enable immersive branded experiences. Use for AR advertising.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "effect_id": {"type": "string"},
                    },
                    "required": ["ad_account_id", "effect_id"],
                },
            ),
            partial(create_spark_ar_effect_ad_handler, client),
        ),
        "meta.ar_vr.create_virtual_tryon": (
            mcp_types.Tool(
                name="meta.ar_vr.create_virtual_tryon",
                description="Create virtual try-on campaigns for fashion, beauty, and eyewear. Let customers try products virtually. Use for AR commerce.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "product_catalog_id": {"type": "string"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(create_virtual_tryon_campaign_handler, client),
        ),
        "meta.ar_vr.create_3d_showcase": (
            mcp_types.Tool(
                name="meta.ar_vr.create_3d_showcase",
                description="Create 3D product showcase ads with interactive rotation and zoom. Display products from all angles. Use for immersive product ads.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "product_id": {"type": "string"},
                        "model_3d_url": {"type": "string"},
                    },
                    "required": ["product_id"],
                },
            ),
            partial(create_3d_product_showcase_handler, client),
        ),
        "meta.ar_vr.create_ar_shopping": (
            mcp_types.Tool(
                name="meta.ar_vr.create_ar_shopping",
                description="Create AR shopping experiences for furniture, home decor placement. Visualize products in real space. Use for AR commerce.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "product_id": {"type": "string"},
                        "product_category": {"type": "string"},
                    },
                    "required": ["product_id"],
                },
            ),
            partial(create_ar_shopping_experience_handler, client),
        ),
        "meta.ar_vr.create_horizon_ad": (
            mcp_types.Tool(
                name="meta.ar_vr.create_horizon_ad",
                description="Create Meta Horizon (Quest) VR ads for immersive virtual reality advertising. Reach VR headset users. Use for VR marketing.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "vr_experience_url": {"type": "string"},
                    },
                    "required": ["ad_account_id", "vr_experience_url"],
                },
            ),
            partial(create_meta_horizon_ad_handler, client),
        ),
        "meta.ar_vr.get_analytics": (
            mcp_types.Tool(
                name="meta.ar_vr.get_analytics",
                description="Get AR performance analytics including effect usage, shares, and engagement. Track AR ad effectiveness. Use for AR reporting.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ar_effect_id": {"type": "string"},
                    },
                    "required": ["ar_effect_id"],
                },
            ),
            partial(get_ar_performance_analytics_handler, client),
        ),
    }
