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

async def analyze_video_retention_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..video_intelligence import VideoIntelligenceEngine
        engine = VideoIntelligenceEngine(client)
        return await engine.analyze_video_retention(arguments)
    except Exception as exc:
        logger.error("tool_analyze_video_retention_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def optimize_sound_strategy_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..video_intelligence import VideoIntelligenceEngine
        engine = VideoIntelligenceEngine(client)
        return await engine.optimize_sound_strategy(arguments)
    except Exception as exc:
        logger.error("tool_optimize_sound_strategy_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_intelligence import VideoIntelligenceEngine
        engine = VideoIntelligenceEngine(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_intelligence import VideoIntelligenceEngine
        engine = VideoIntelligenceEngine(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_video_hook_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..video_intelligence import VideoIntelligenceEngine
        engine = VideoIntelligenceEngine(client)
        return await engine.analyze_video_hook(arguments)
    except Exception as exc:
        logger.error("tool_analyze_video_hook_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def check_video_accessibility_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..video_intelligence import VideoIntelligenceEngine
        engine = VideoIntelligenceEngine(client)
        return await engine.check_video_accessibility(arguments)
    except Exception as exc:
        logger.error("tool_check_video_accessibility_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.analyze_quality": (
            mcp_types.Tool(
                name="meta.video.analyze_quality",
                description="Analyze video quality metrics including resolution, bitrate, and encoding. Score technical quality. Use for video QA.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "video_id": {"type": "string"},
                    },
                    "required": ["video_id"],
                },
            ),
            partial(analyze_video_quality_handler, client),
        ),
        "meta.video.analyze_retention": (
            mcp_types.Tool(
                name="meta.video.analyze_retention",
                description="Analyze video retention curve and drop-off points. Identify where viewers leave. Use for video content optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "video_id": {"type": "string"},
                    },
                    "required": ["video_id"],
                },
            ),
            partial(analyze_video_retention_handler, client),
        ),
        "meta.video.optimize_sound": (
            mcp_types.Tool(
                name="meta.video.optimize_sound",
                description="Optimize sound strategy for sound-on vs sound-off viewers. Add captions and music recommendations. Use for audio optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "video_id": {"type": "string"},
                    },
                    "required": ["video_id"],
                },
            ),
            partial(optimize_sound_strategy_handler, client),
        ),
        "meta.video.test_thumbnails": (
            mcp_types.Tool(
                name="meta.video.test_thumbnails",
                description="Test and score video thumbnails for click-through rate potential. Compare thumbnail variants. Use for thumbnail optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "video_id": {"type": "string"},
                        "thumbnails": {"type": "array"},
                    },
                    "required": ["video_id"],
                },
            ),
            partial(test_video_thumbnails_handler, client),
        ),
        "meta.video.optimize_length": (
            mcp_types.Tool(
                name="meta.video.optimize_length",
                description="Optimize video duration based on objective and placement. Recommend ideal length. Use for video format optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "video_id": {"type": "string"},
                        "campaign_objective": {"type": "string"},
                    },
                    "required": ["video_id"],
                },
            ),
            partial(optimize_video_length_handler, client),
        ),
        "meta.video.analyze_hook": (
            mcp_types.Tool(
                name="meta.video.analyze_hook",
                description="Analyze first 3 seconds (hook) for attention capture. Score opening engagement potential. Use for hook optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "video_id": {"type": "string"},
                        "generate_alternatives": {"type": "boolean"},
                    },
                    "required": ["video_id"],
                },
            ),
            partial(analyze_video_hook_handler, client),
        ),
        "meta.video.check_accessibility": (
            mcp_types.Tool(
                name="meta.video.check_accessibility",
                description="Check video accessibility compliance including captions, contrast, and audio descriptions. Verify WCAG standards. Use for accessibility audit.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "video_id": {"type": "string"},
                        "compliance_standards": {"type": "array"},
                    },
                    "required": ["video_id"],
                },
            ),
            partial(check_video_accessibility_handler, client),
        ),
    }
