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

async def check_compliance_requirements_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..brand_safety import BrandSafetyEngine
        engine = BrandSafetyEngine(client)
        return await engine.check_compliance_requirements(arguments)
    except Exception as exc:
        logger.error("tool_check_compliance_requirements_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def analyze_content_suitability_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..brand_safety import BrandSafetyEngine
        engine = BrandSafetyEngine(client)
        return await engine.analyze_content_suitability(arguments)
    except Exception as exc:
        logger.error("tool_analyze_content_suitability_failed", error=str(exc))
        return ToolResult(ok=False, error={"message": str(exc)})

async def predict_ad_approval_handler(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    try:
        from ..brand_safety import BrandSafetyEngine
        engine = BrandSafetyEngine(client)
        return await engine.predict_ad_approval(arguments)
    except Exception as exc:
        logger.error("tool_predict_ad_approval_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.brand_safety.manage_block_lists": (
            mcp_types.Tool(
                name="meta.brand_safety.manage_block_lists",
                description="Manage block lists for brand safety. Add/remove domains, publishers, and content categories. Use for brand protection.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "action": {"type": "string"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(manage_block_lists_handler, client),
        ),
        "meta.brand_safety.check_compliance": (
            mcp_types.Tool(
                name="meta.brand_safety.check_compliance",
                description="Check compliance requirements for special ad categories (housing, credit, employment). Verify legal requirements. Use for compliance audits.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "special_ad_categories": {"type": "array"},
                    },
                    "required": ["ad_account_id"],
                },
            ),
            partial(check_compliance_requirements_handler, client),
        ),
        "meta.brand_safety.analyze_suitability": (
            mcp_types.Tool(
                name="meta.brand_safety.analyze_suitability",
                description="Analyze content suitability and brand risk for ad placements. Score placement quality. Use for brand safety assessment.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_id": {"type": "string"},
                    },
                    "required": ["ad_id"],
                },
            ),
            partial(analyze_content_suitability_handler, client),
        ),
        "meta.brand_safety.predict_approval": (
            mcp_types.Tool(
                name="meta.brand_safety.predict_approval",
                description="Predict ad approval likelihood before submission. Identify potential policy violations. Use for pre-submission review.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_creative": {"type": "object"},
                    },
                    "required": ["ad_creative"],
                },
            ),
            partial(predict_ad_approval_handler, client),
        ),
    }
