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

async def manage_product_tagging_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..instagram_shopping import InstagramShoppingEngine
        engine = InstagramShoppingEngine(client)
        return await engine.manage_product_tagging(arguments)
    except Exception as exc:
        logger.error("tool_manage_product_tagging_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def get_shop_analytics_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..instagram_shopping import InstagramShoppingEngine
        engine = InstagramShoppingEngine(client)
        return await engine.get_shop_analytics(arguments)
    except Exception as exc:
        logger.error("tool_get_shop_analytics_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def schedule_live_shopping_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..instagram_shopping import InstagramShoppingEngine
        engine = InstagramShoppingEngine(client)
        return await engine.schedule_live_shopping(arguments)
    except Exception as exc:
        logger.error("tool_schedule_live_shopping_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def build_product_collections_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..instagram_shopping import InstagramShoppingEngine
        engine = InstagramShoppingEngine(client)
        return await engine.build_product_collections(arguments)
    except Exception as exc:
        logger.error("tool_build_product_collections_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def create_shop_ad_campaign_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..instagram_shopping import InstagramShoppingEngine
        engine = InstagramShoppingEngine(client)
        return await engine.create_shop_ad_campaign(arguments)
    except Exception as exc:
        logger.error("tool_create_shop_ad_campaign_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def optimize_instagram_checkout_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..instagram_shopping import InstagramShoppingEngine
        engine = InstagramShoppingEngine(client)
        return await engine.optimize_instagram_checkout(arguments)
    except Exception as exc:
        logger.error("tool_optimize_instagram_checkout_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def create_shoppable_story_templates_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..instagram_shopping import InstagramShoppingEngine
        engine = InstagramShoppingEngine(client)
        return await engine.create_shoppable_story_templates(arguments)
    except Exception as exc:
        logger.error("tool_create_shoppable_story_templates_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.commerce.create_instagram_shop": (
            mcp_types.Tool(
                name="meta.commerce.create_instagram_shop",
                description="Create Instagram Shop for social commerce. Connect catalog and enable in-app shopping. Use for ecommerce setup on Instagram.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "business_id": {"type": "string"},
                        "catalog_id": {"type": "string"},
                    },
                    "required": ["business_id"],
                },
            ),
            partial(create_instagram_shop_handler, client),
        ),
        "meta.commerce.tag_products": (
            mcp_types.Tool(
                name="meta.commerce.tag_products",
                description="Tag products in posts, stories, and reels for shoppable content. Enable direct product discovery. Use for social commerce optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "media_id": {"type": "string"},
                        "tags": {"type": "array"},
                    },
                    "required": ["media_id"],
                },
            ),
            partial(manage_product_tagging_handler, client),
        ),
        "meta.commerce.get_analytics": (
            mcp_types.Tool(
                name="meta.commerce.get_analytics",
                description="Get shop analytics including product views, saves, and purchases. Track conversion funnel. Use for social commerce reporting.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "commerce_account_id": {"type": "string"},
                    },
                    "required": ["commerce_account_id"],
                },
            ),
            partial(get_shop_analytics_handler, client),
        ),
        "meta.commerce.schedule_live": (
            mcp_types.Tool(
                name="meta.commerce.schedule_live",
                description="Schedule live shopping event on Instagram Live. Enable real-time product showcasing. Use for live commerce events.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "page_id": {"type": "string"},
                        "start_time": {"type": "string"},
                    },
                    "required": ["page_id", "start_time"],
                },
            ),
            partial(schedule_live_shopping_handler, client),
        ),
        "meta.commerce.build_collections": (
            mcp_types.Tool(
                name="meta.commerce.build_collections",
                description="Build curated product collections for shop storefront. Group products by theme or category. Use for merchandising.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "catalog_id": {"type": "string"},
                        "name": {"type": "string"},
                    },
                    "required": ["catalog_id", "name"],
                },
            ),
            partial(build_product_collections_handler, client),
        ),
        "meta.commerce.create_ad_campaign": (
            mcp_types.Tool(
                name="meta.commerce.create_ad_campaign",
                description="Create shop ad campaign with catalog integration. Drive traffic to Instagram Shop. Use for social commerce advertising.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "catalog_id": {"type": "string"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(create_shop_ad_campaign_handler, client),
        ),
        "meta.commerce.optimize_checkout": (
            mcp_types.Tool(
                name="meta.commerce.optimize_checkout",
                description="Optimize Instagram checkout flow for higher conversion rates. Reduce friction and abandonment. Use for checkout optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "commerce_account_id": {"type": "string"},
                    },
                    "required": ["commerce_account_id"],
                },
            ),
            partial(optimize_instagram_checkout_handler, client),
        ),
        "meta.commerce.create_story_templates": (
            mcp_types.Tool(
                name="meta.commerce.create_story_templates",
                description="Create shoppable story templates with product stickers. Enable swipe-up shopping experiences. Use for stories commerce.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "template_type": {"type": "string"},
                    },
                    "required": ["template_type"],
                },
            ),
            partial(create_shoppable_story_templates_handler, client),
        ),
    }
