"""
Threads Ads Tools
Wraps the ThreadsAdsEngine to provide tools for advertising on Threads.
"""

from typing import Dict, Any, Tuple
from functools import partial
import mcp.types as mcp_types

from ..meta_client import MetaClient
from ..schemas import ToolResult
from ..threads_ads import get_threads_ads_engine
from .base import ToolHandler


async def get_threads_user_id(
    client: MetaClient,
    arguments: Dict[str, Any]
) -> ToolResult:
    """Get Threads user ID for an Instagram account."""
    engine = get_threads_ads_engine()
    engine.client = client
    return await engine.get_threads_user_id(arguments)


async def create_instagram_backed_threads(
    client: MetaClient,
    arguments: Dict[str, Any]
) -> ToolResult:
    """Create Instagram-backed Threads account."""
    engine = get_threads_ads_engine()
    engine.client = client
    return await engine.create_instagram_backed_threads(arguments)


async def create_threads_ad_set(
    client: MetaClient,
    arguments: Dict[str, Any]
) -> ToolResult:
    """Create ad set targeting Threads."""
    engine = get_threads_ads_engine()
    engine.client = client
    return await engine.create_threads_ad_set(arguments)


async def create_threads_creative(
    client: MetaClient,
    arguments: Dict[str, Any]
) -> ToolResult:
    """Create creative with threads_user_id."""
    engine = get_threads_ads_engine()
    engine.client = client
    return await engine.create_threads_creative(arguments)


async def create_threads_ad(
    client: MetaClient,
    arguments: Dict[str, Any]
) -> ToolResult:
    """Create Threads ad."""
    engine = get_threads_ads_engine()
    engine.client = client
    return await engine.create_threads_ad(arguments)


async def get_threads_insights(
    client: MetaClient,
    arguments: Dict[str, Any]
) -> ToolResult:
    """Get Threads placement insights."""
    engine = get_threads_ads_engine()
    engine.client = client
    return await engine.get_threads_insights(arguments)


def get_tools(client: MetaClient) -> Dict[str, Tuple[mcp_types.Tool, ToolHandler]]:
    """Register Threads ads tools"""
    return {
        "meta.threads.get_user_id": (
            mcp_types.Tool(
                name="meta.threads.get_user_id",
                description="Get the Threads User ID linked to an Instagram account. Required for creating Threads ads. Use for Threads advertising setup.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "instagram_user_id": {"type": "string", "description": "Instagram user ID"}
                    },
                    "required": ["instagram_user_id"]
                }
            ),
            partial(get_threads_user_id, client)
        ),
        "meta.threads.create_backed_account": (
            mcp_types.Tool(
                name="meta.threads.create_backed_account",
                description="Create an Instagram-backed Threads account for advertising. Enables Threads ads without a full Threads account. Use for Threads onboarding.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "business_id": {"type": "string", "description": "Business ID"},
                        "instagram_user_id": {"type": "string", "description": "Instagram user ID to link"}
                    },
                    "required": ["business_id", "instagram_user_id"]
                }
            ),
            partial(create_instagram_backed_threads, client)
        ),
        "meta.threads.create_adset": (
            mcp_types.Tool(
                name="meta.threads.create_adset",
                description="Create an ad set targeting Threads stream placement. Supports combining with Instagram stream placement. Use for Threads campaign creation.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "campaign_id": {"type": "string"},
                        "name": {"type": "string"},
                        "daily_budget": {"type": "integer", "description": "Daily budget in cents"},
                        "optimization_goal": {"type": "string", "enum": ["LINK_CLICKS", "IMPRESSIONS", "REACH", "CONVERSIONS"]},
                        "targeting_countries": {"type": "array", "items": {"type": "string"}},
                        "include_instagram": {"type": "boolean", "description": "Also target Instagram stream", "default": True},
                        "bid_amount": {"type": "integer", "description": "Bid amount in cents (optional)"}
                    },
                    "required": ["ad_account_id", "campaign_id", "name", "daily_budget"]
                }
            ),
            partial(create_threads_ad_set, client)
        ),
        "meta.threads.create_creative": (
            mcp_types.Tool(
                name="meta.threads.create_creative",
                description="Create ad creative with threads_user_id for Threads placements. Supports image and video formats. Use for Threads creative creation.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "name": {"type": "string"},
                        "threads_user_id": {"type": "string", "description": "Threads user ID"},
                        "instagram_user_id": {"type": "string", "description": "Associated Instagram user ID"},
                        "page_id": {"type": "string", "description": "Facebook Page ID"},
                        "message": {"type": "string", "description": "Ad copy text"},
                        "link": {"type": "string", "description": "Destination URL"},
                        "image_hash": {"type": "string", "description": "Image hash (or use video_id)"},
                        "video_id": {"type": "string", "description": "Video ID (or use image_hash)"},
                        "call_to_action": {"type": "string", "enum": ["LEARN_MORE", "SHOP_NOW", "SIGN_UP", "WATCH_MORE"]}
                    },
                    "required": ["ad_account_id", "threads_user_id", "instagram_user_id", "page_id"]
                }
            ),
            partial(create_threads_creative, client)
        ),
        "meta.threads.create_ad": (
            mcp_types.Tool(
                name="meta.threads.create_ad",
                description="Create a Threads ad linking creative to ad set. Final step in Threads campaign setup. Use for Threads ad activation.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "name": {"type": "string"},
                        "adset_id": {"type": "string"},
                        "creative_id": {"type": "string"}
                    },
                    "required": ["ad_account_id", "adset_id", "creative_id"]
                }
            ),
            partial(create_threads_ad, client)
        ),
        "meta.threads.get_insights": (
            mcp_types.Tool(
                name="meta.threads.get_insights",
                description="Get performance insights broken down by Threads placement vs other placements. Analyze Threads-specific metrics. Use for Threads performance analysis.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "object_id": {"type": "string", "description": "Campaign, ad set, or ad ID"},
                        "level": {"type": "string", "enum": ["campaign", "adset", "ad"]},
                        "time_range": {
                            "type": "object",
                            "properties": {
                                "since": {"type": "string"},
                                "until": {"type": "string"}
                            }
                        }
                    },
                    "required": ["object_id"]
                }
            ),
            partial(get_threads_insights, client)
        )
    }
