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

async def optimize_reels_creative_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..reels_video import ReelsVideoEngine
        engine = ReelsVideoEngine(client)
        return await engine.optimize_reels_creative(arguments)
    except Exception as exc:
        logger.error("tool_optimize_reels_creative_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def get_reels_performance_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..reels_video import ReelsVideoEngine
        engine = ReelsVideoEngine(client)
        return await engine.get_reels_performance(arguments)
    except Exception as exc:
        logger.error("tool_get_reels_performance_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def build_reels_audience_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..reels_video import ReelsVideoEngine
        engine = ReelsVideoEngine(client)
        return await engine.build_reels_audience(arguments)
    except Exception as exc:
        logger.error("tool_build_reels_audience_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def cross_post_reels_to_stories_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..reels_video import ReelsVideoEngine
        engine = ReelsVideoEngine(client)
        return await engine.cross_post_reels_to_stories(arguments)
    except Exception as exc:
        logger.error("tool_cross_post_reels_to_stories_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def analyze_reels_sound_strategy_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..reels_video import ReelsVideoEngine
        engine = ReelsVideoEngine(client)
        return await engine.analyze_reels_sound_strategy(arguments)
    except Exception as exc:
        logger.error("tool_analyze_reels_sound_strategy_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def optimize_reels_hashtags_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..reels_video import ReelsVideoEngine
        engine = ReelsVideoEngine(client)
        return await engine.optimize_reels_hashtags(arguments)
    except Exception as exc:
        logger.error("tool_optimize_reels_hashtags_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def predict_reels_engagement_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..reels_video import ReelsVideoEngine
        engine = ReelsVideoEngine(client)
        return await engine.predict_reels_engagement(arguments)
    except Exception as exc:
        logger.error("tool_predict_reels_engagement_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.reels.create_campaign": (
            mcp_types.Tool(
                name="meta.reels.create_campaign",
                description="Create Reels-first advertising campaign. Optimize for vertical short-form video placements. Use for Instagram and Facebook Reels ads.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "campaign_name": {"type": "string"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(create_reels_campaign_handler, client),
        ),
        "meta.reels.optimize_creative": (
            mcp_types.Tool(
                name="meta.reels.optimize_creative",
                description="Optimize Reels creative for engagement. Analyze hook, pacing, and format best practices. Use for short-form video optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "video_id": {"type": "string"},
                    },
                    "required": ["video_id"],
                },
            ),
            partial(optimize_reels_creative_handler, client),
        ),
        "meta.reels.get_performance": (
            mcp_types.Tool(
                name="meta.reels.get_performance",
                description="Get Reels ad performance including watch time, completion rate, and engagement. Analyze video-specific metrics. Use for Reels analytics.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_id": {"type": "string"},
                    },
                    "required": ["ad_id"],
                },
            ),
            partial(get_reels_performance_handler, client),
        ),
        "meta.reels.build_audience": (
            mcp_types.Tool(
                name="meta.reels.build_audience",
                description="Build custom audience from Reels engagement. Retarget viewers, likers, and commenters. Use for video engagement remarketing.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "name": {"type": "string"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(build_reels_audience_handler, client),
        ),
        "meta.reels.cross_post": (
            mcp_types.Tool(
                name="meta.reels.cross_post",
                description="Cross-post Reels to Stories and Feed for maximum reach. Extend content across placements. Use for multi-placement distribution.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "video_id": {"type": "string"},
                    },
                    "required": ["video_id"],
                },
            ),
            partial(cross_post_reels_to_stories_handler, client),
        ),
        "meta.reels.analyze_sound": (
            mcp_types.Tool(
                name="meta.reels.analyze_sound",
                description="Analyze Reels sound strategy including trending audio and music. Find viral sounds for better reach. Use for audio optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "category": {"type": "string"},
                    },
                    "required": ["category"],
                },
            ),
            partial(analyze_reels_sound_strategy_handler, client),
        ),
        "meta.reels.optimize_hashtags": (
            mcp_types.Tool(
                name="meta.reels.optimize_hashtags",
                description="Optimize Reels hashtags for discovery. Find trending and relevant hashtags by category. Use for organic reach optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "content_category": {"type": "string"},
                    },
                    "required": ["content_category"],
                },
            ),
            partial(optimize_reels_hashtags_handler, client),
        ),
        "meta.reels.predict_engagement": (
            mcp_types.Tool(
                name="meta.reels.predict_engagement",
                description="Predict Reels engagement based on video elements. Score hook, format, and content quality. Use for creative pre-testing.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "video_elements": {"type": "object"},
                    },
                    "required": ["video_elements"],
                },
            ),
            partial(predict_reels_engagement_handler, client),
        ),
    }
