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 analyze_video_retention_heatmap_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..video_reels_mastery import VideoReelsMasteryEngine
        engine = VideoReelsMasteryEngine(client)
        return await engine.analyze_video_retention_heatmap(arguments) # uses argument dict named request in engine? no, engine takes 'request' which is Dict in signature
    except Exception as exc:
        logger.error("tool_analyze_video_retention_heatmap_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def analyze_hook_effectiveness_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..video_reels_mastery import VideoReelsMasteryEngine
        engine = VideoReelsMasteryEngine(client)
        return await engine.analyze_hook_effectiveness(arguments)
    except Exception as exc:
        logger.error("tool_analyze_hook_effectiveness_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def compare_sound_on_off_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..video_reels_mastery import VideoReelsMasteryEngine
        engine = VideoReelsMasteryEngine(client)
        return await engine.compare_sound_on_off(arguments)
    except Exception as exc:
        logger.error("tool_compare_sound_on_off_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def optimize_reels_performance_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..video_reels_mastery import VideoReelsMasteryEngine
        engine = VideoReelsMasteryEngine(client)
        return await engine.optimize_reels_performance(arguments)
    except Exception as exc:
        logger.error("tool_optimize_reels_performance_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def test_video_thumbnails_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..video_reels_mastery import VideoReelsMasteryEngine
        engine = VideoReelsMasteryEngine(client)
        return await engine.test_video_thumbnails(arguments)
    except Exception as exc:
        logger.error("tool_test_video_thumbnails_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def optimize_video_length_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..video_reels_mastery import VideoReelsMasteryEngine
        engine = VideoReelsMasteryEngine(client)
        return await engine.optimize_video_length(arguments)
    except Exception as exc:
        logger.error("tool_optimize_video_length_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def analyze_engagement_patterns_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..video_reels_mastery import VideoReelsMasteryEngine
        engine = VideoReelsMasteryEngine(client)
        return await engine.analyze_engagement_patterns(arguments)
    except Exception as exc:
        logger.error("tool_analyze_engagement_patterns_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def optimize_cta_placement_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..video_reels_mastery import VideoReelsMasteryEngine
        engine = VideoReelsMasteryEngine(client)
        return await engine.optimize_cta_placement(arguments)
    except Exception as exc:
        logger.error("tool_optimize_cta_placement_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.video_mastery.analyze_retention": (
            mcp_types.Tool(
                name="meta.video_mastery.analyze_retention",
                description="Analyze video retention heatmap showing where viewers drop off. Identify weak points in video content. Use for video content optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_ids": {"type": "array", "items": {"type": "string"}},
                    },
                    "required": ["ad_ids"],
                },
            ),
            partial(analyze_video_retention_heatmap_handler, client),
        ),
        "meta.video_mastery.analyze_hook": (
            mcp_types.Tool(
                name="meta.video_mastery.analyze_hook",
                description="Analyze hook effectiveness in first 3 seconds. Score attention capture and thumb-stop rate. Use for video hook optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_ids": {"type": "array", "items": {"type": "string"}},
                    },
                    "required": ["ad_ids"],
                },
            ),
            partial(analyze_hook_effectiveness_handler, client),
        ),
        "meta.video_mastery.compare_sound": (
            mcp_types.Tool(
                name="meta.video_mastery.compare_sound",
                description="Compare video performance with sound on vs sound off. Analyze audio dependency. Use for audio strategy optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_ids": {"type": "array", "items": {"type": "string"}},
                    },
                    "required": ["ad_ids"],
                },
            ),
            partial(compare_sound_on_off_handler, client),
        ),
        "meta.video_mastery.optimize_reels": (
            mcp_types.Tool(
                name="meta.video_mastery.optimize_reels",
                description="Optimize Reels performance with format-specific recommendations. Apply short-form video best practices. Use for Reels optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_ids": {"type": "array", "items": {"type": "string"}},
                    },
                    "required": ["ad_ids"],
                },
            ),
            partial(optimize_reels_performance_handler, client),
        ),
        "meta.video_mastery.test_thumbnails": (
            mcp_types.Tool(
                name="meta.video_mastery.test_thumbnails",
                description="Test video thumbnails for click-through rate impact. Compare thumbnail variants. Use for thumbnail A/B testing.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_set_id": {"type": "string"},
                    },
                    "required": ["ad_set_id"],
                },
            ),
            partial(test_video_thumbnails_handler, client),
        ),
        "meta.video_mastery.optimize_length": (
            mcp_types.Tool(
                name="meta.video_mastery.optimize_length",
                description="Optimize video length based on objective and audience attention span. Recommend ideal duration. Use for video format optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(optimize_video_length_handler, client),
        ),
        "meta.video_mastery.analyze_engagement": (
            mcp_types.Tool(
                name="meta.video_mastery.analyze_engagement",
                description="Analyze video engagement patterns including likes, shares, and comments timing. Identify viral potential. Use for engagement analysis.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_ids": {"type": "array", "items": {"type": "string"}},
                    },
                    "required": ["ad_ids"],
                },
            ),
            partial(analyze_engagement_patterns_handler, client),
        ),
        "meta.video_mastery.optimize_cta": (
            mcp_types.Tool(
                name="meta.video_mastery.optimize_cta",
                description="Optimize CTA (call-to-action) placement timing and design. Find optimal conversion moment. Use for CTA optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_ids": {"type": "array", "items": {"type": "string"}},
                    },
                    "required": ["ad_ids"],
                },
            ),
            partial(optimize_cta_placement_handler, client),
        ),
    }
