"""
Cross-Channel Conversion Optimization Tools
Wraps the CCCOEngine for app+web unified optimization.
"""

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 ..ccco import get_ccco_engine
from .base import ToolHandler


async def create_ccco_campaign(
    client: MetaClient,
    arguments: Dict[str, Any]
) -> ToolResult:
    """Create CCCO campaign."""
    engine = get_ccco_engine()
    engine.client = client
    return await engine.create_ccco_campaign(arguments)


async def create_ccco_adset(
    client: MetaClient,
    arguments: Dict[str, Any]
) -> ToolResult:
    """Create CCCO ad set."""
    engine = get_ccco_engine()
    engine.client = client
    return await engine.create_ccco_adset(arguments)


async def get_ccco_insights(
    client: MetaClient,
    arguments: Dict[str, Any]
) -> ToolResult:
    """Get CCCO insights."""
    engine = get_ccco_engine()
    engine.client = client
    return await engine.get_ccco_insights(arguments)


async def validate_ccco_setup(
    client: MetaClient,
    arguments: Dict[str, Any]
) -> ToolResult:
    """Validate CCCO prerequisites."""
    engine = get_ccco_engine()
    engine.client = client
    return await engine.validate_ccco_setup(arguments)


def get_tools(client: MetaClient) -> Dict[str, Tuple[mcp_types.Tool, ToolHandler]]:
    """Register CCCO tools"""
    return {
        "meta.ccco.create_campaign": (
            mcp_types.Tool(
                name="meta.ccco.create_campaign",
                description="Create a Cross-Channel Conversion Optimization campaign that optimizes for conversions across both app and web.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "campaign_name": {"type": "string"},
                        "daily_budget": {"type": "integer", "description": "Daily budget in cents"},
                        "app_id": {"type": "string", "description": "Application ID"},
                        "app_store_urls": {
                            "type": "array", 
                            "items": {"type": "string"},
                            "description": "Play Store and/or App Store URLs"
                        },
                        "pixel_id": {"type": "string", "description": "Pixel ID"},
                        "event_type": {
                            "type": "string", 
                            "enum": ["PURCHASE", "ADD_TO_CART", "COMPLETE_REGISTRATION", "LEAD", "INITIATED_CHECKOUT"],
                            "default": "PURCHASE"
                        },
                        "targeting_countries": {"type": "array", "items": {"type": "string"}}
                    },
                    "required": ["ad_account_id", "campaign_name", "daily_budget", "app_id", "pixel_id"]
                }
            ),
            partial(create_ccco_campaign, client)
        ),
        "meta.ccco.create_adset": (
            mcp_types.Tool(
                name="meta.ccco.create_adset",
                description="Create an ad set with omnichannel_object for existing CCCO campaign.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "campaign_id": {"type": "string"},
                        "name": {"type": "string"},
                        "daily_budget": {"type": "integer"},
                        "app_config": {
                            "type": "object",
                            "properties": {
                                "application_id": {"type": "string"},
                                "event_type": {"type": "string"},
                                "object_store_urls": {"type": "array", "items": {"type": "string"}}
                            },
                            "required": ["application_id"]
                        },
                        "pixel_config": {
                            "type": "object",
                            "properties": {
                                "pixel_id": {"type": "string"},
                                "event_type": {"type": "string"}
                            },
                            "required": ["pixel_id"]
                        },
                        "targeting_countries": {"type": "array", "items": {"type": "string"}}
                    },
                    "required": ["ad_account_id", "campaign_id", "name", "daily_budget", "app_config", "pixel_config"]
                }
            ),
            partial(create_ccco_adset, client)
        ),
        "meta.ccco.get_insights": (
            mcp_types.Tool(
                name="meta.ccco.get_insights",
                description="Get insights for CCCO campaigns with app vs web conversion breakdown.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "object_id": {"type": "string", "description": "Campaign or ad set ID"},
                        "time_range": {
                            "type": "object",
                            "properties": {
                                "since": {"type": "string"},
                                "until": {"type": "string"}
                            }
                        }
                    },
                    "required": ["object_id"]
                }
            ),
            partial(get_ccco_insights, client)
        ),
        "meta.ccco.validate": (
            mcp_types.Tool(
                name="meta.ccco.validate",
                description="Validate that CCCO prerequisites are met (app SDK and pixel properly configured).",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "app_id": {"type": "string"},
                        "pixel_id": {"type": "string"},
                        "event_type": {"type": "string", "default": "PURCHASE"}
                    },
                    "required": ["ad_account_id", "app_id", "pixel_id"]
                }
            ),
            partial(validate_ccco_setup, client)
        )
    }
