"""Advantage+ campaign tools."""

from __future__ import annotations

from functools import partial
from typing import Any, Dict, Tuple

import mcp.types as mcp_types

from ..advantage_plus import get_advantage_plus_engine
from ..meta_client import MetaClient
from ..schemas import MigrateToAdvantagePlusRequest, ToolResult
from .base import ToolHandler


def _engine(client: MetaClient):
    engine = get_advantage_plus_engine()
    engine.client = client
    return engine


async def create_advantage_shopping_campaign(
    client: MetaClient,
    arguments: Dict[str, Any],
) -> ToolResult:
    return await _engine(client).create_advantage_shopping_campaign(arguments)


async def create_advantage_app_campaign(
    client: MetaClient,
    arguments: Dict[str, Any],
) -> ToolResult:
    return await _engine(client).create_advantage_app_campaign(arguments)


async def enable_advantage_creative(
    client: MetaClient,
    arguments: Dict[str, Any],
) -> ToolResult:
    return await _engine(client).enable_advantage_creative(arguments)


async def enable_advantage_placements(
    client: MetaClient,
    arguments: Dict[str, Any],
) -> ToolResult:
    return await _engine(client).enable_advantage_placements(arguments)


async def enable_advantage_audience(
    client: MetaClient,
    arguments: Dict[str, Any],
) -> ToolResult:
    return await _engine(client).enable_advantage_audience(arguments)


async def enable_advantage_budget(
    client: MetaClient,
    arguments: Dict[str, Any],
) -> ToolResult:
    return await _engine(client).enable_advantage_budget(arguments)


async def create_advantage_catalog_ads(
    client: MetaClient,
    arguments: Dict[str, Any],
) -> ToolResult:
    return await _engine(client).create_advantage_catalog_ads(arguments)


async def monitor_advantage_performance(
    client: MetaClient,
    arguments: Dict[str, Any],
) -> ToolResult:
    return await _engine(client).monitor_advantage_performance(arguments)


async def migrate_to_advantage_plus(
    client: MetaClient,
    arguments: Dict[str, Any],
) -> ToolResult:
    payload = MigrateToAdvantagePlusRequest.model_validate(arguments)
    return await _engine(client).migrate_to_advantage_plus(payload.model_dump())


async def check_v24_readiness(
    client: MetaClient,
    arguments: Dict[str, Any],
) -> ToolResult:
    # Static policy guidance for breaking-change fields that cannot be inferred
    # from one endpoint without full account crawling.
    return ToolResult(
        ok=True,
        data={
            "api_version": arguments.get("api_version", "v24.0"),
            "checks": [
                {
                    "id": "dynamic_media_default",
                    "status": "required",
                    "message": "Set dynamic_media_default for Advantage+ catalog ads to avoid implicit defaults.",
                },
                {
                    "id": "is_adset_budget_sharing_enabled",
                    "status": "required",
                    "message": "Use is_adset_budget_sharing_enabled for ad set budget sharing on campaign creation.",
                },
                {
                    "id": "facebook_video_feeds_deprecation",
                    "status": "required",
                    "message": "Remove deprecated facebook video_feeds placements and use supported alternatives.",
                },
                {
                    "id": "ctmlg_deprecation",
                    "status": "required",
                    "message": "Plan and execute CTMLG migration before endpoint sunset to avoid runtime failures.",
                },
            ],
        },
    )


def get_tools(client: MetaClient) -> Dict[str, Tuple[mcp_types.Tool, ToolHandler]]:
    return {
        "meta.advantage.create_shopping_campaign": (
            mcp_types.Tool(
                name="meta.advantage.create_shopping_campaign",
                description="Create an Advantage+ shopping campaign with AI optimization for audience, creative, placements, and budget distribution.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "campaign_name": {"type": "string"},
                        "catalog_id": {"type": "string"},
                        "daily_budget": {"type": "integer"},
                        "is_adset_budget_sharing_enabled": {"type": "boolean"},
                        "dynamic_media_default": {"type": ["boolean", "string"]},
                    },
                    "required": ["ad_account_id", "campaign_name", "catalog_id", "daily_budget"],
                },
            ),
            partial(create_advantage_shopping_campaign, client),
        ),
        "meta.advantage.create_app_campaign": (
            mcp_types.Tool(
                name="meta.advantage.create_app_campaign",
                description="Create an Advantage+ app campaign for app install and in-app event optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "campaign_name": {"type": "string"},
                        "app_id": {"type": "string"},
                        "daily_budget": {"type": "integer"},
                    },
                    "required": ["ad_account_id", "campaign_name", "app_id", "daily_budget"],
                },
            ),
            partial(create_advantage_app_campaign, client),
        ),
        "meta.advantage.enable_creative": (
            mcp_types.Tool(
                name="meta.advantage.enable_creative",
                description="Enable or disable Advantage+ creative (dynamic creative) on an ad set.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "adset_id": {"type": "string"},
                        "enable": {"type": "boolean", "default": True},
                    },
                    "required": ["adset_id"],
                },
            ),
            partial(enable_advantage_creative, client),
        ),
        "meta.advantage.enable_placements": (
            mcp_types.Tool(
                name="meta.advantage.enable_placements",
                description="Enable Advantage+ placements so Meta can optimize cross-platform placement delivery automatically.",
                inputSchema={
                    "type": "object",
                    "properties": {"adset_id": {"type": "string"}},
                    "required": ["adset_id"],
                },
            ),
            partial(enable_advantage_placements, client),
        ),
        "meta.advantage.enable_audience": (
            mcp_types.Tool(
                name="meta.advantage.enable_audience",
                description="Enable Advantage+ audience expansion on an ad set using broad targeting and optional seeds.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "adset_id": {"type": "string"},
                        "suggestions": {"type": "object"},
                    },
                    "required": ["adset_id"],
                },
            ),
            partial(enable_advantage_audience, client),
        ),
        "meta.advantage.enable_budget": (
            mcp_types.Tool(
                name="meta.advantage.enable_budget",
                description="Enable campaign-level Advantage budget optimization to automatically distribute budget across ad sets.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "campaign_id": {"type": "string"},
                        "daily_budget": {"type": "integer"},
                    },
                    "required": ["campaign_id", "daily_budget"],
                },
            ),
            partial(enable_advantage_budget, client),
        ),
        "meta.advantage.create_catalog_ads": (
            mcp_types.Tool(
                name="meta.advantage.create_catalog_ads",
                description="Create Advantage+ catalog ads for retargeting or prospecting with dynamic product optimization.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "ad_account_id": {"type": "string"},
                        "campaign_name": {"type": "string"},
                        "catalog_id": {"type": "string"},
                        "daily_budget": {"type": "integer"},
                        "product_set_id": {"type": "string"},
                        "dynamic_media_default": {"type": ["boolean", "string"]},
                    },
                    "required": ["ad_account_id", "campaign_name", "catalog_id", "daily_budget"],
                },
            ),
            partial(create_advantage_catalog_ads, client),
        ),
        "meta.advantage.monitor_performance": (
            mcp_types.Tool(
                name="meta.advantage.monitor_performance",
                description="Analyze Advantage+ campaign performance and return optimization signals and recommendations.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "campaign_id": {"type": "string"},
                        "time_range": {"type": "object"},
                    },
                    "required": ["campaign_id"],
                },
            ),
            partial(monitor_advantage_performance, client),
        ),
        "meta.advantage.migrate_to_advantage_plus": (
            mcp_types.Tool(
                name="meta.advantage.migrate_to_advantage_plus",
                description="Migrate an existing campaign to the Advantage+ structure required by newer Marketing API campaign flows.",
                inputSchema=MigrateToAdvantagePlusRequest.model_json_schema(),
            ),
            partial(migrate_to_advantage_plus, client),
        ),
        "meta.advantage.check_v24_readiness": (
            mcp_types.Tool(
                name="meta.advantage.check_v24_readiness",
                description="Return a compliance checklist for v24 Advantage+ breaking changes including dynamic media, budget-sharing fields, placement deprecations, and CTMLG migration.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "api_version": {"type": "string", "default": "v24.0"},
                    },
                },
            ),
            partial(check_v24_readiness, client),
        ),
    }
