"""
WhatsApp Flows Tools
Wraps the WhatsAppFlowsEngine for structured interactive forms.
"""

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 ..whatsapp_flows import get_whatsapp_flows_engine
from .base import ToolHandler


async def create_flow(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    engine = get_whatsapp_flows_engine()
    engine.client = client
    return await engine.create_flow(arguments)


async def update_flow_json(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    engine = get_whatsapp_flows_engine()
    engine.client = client
    return await engine.update_flow_json(arguments)


async def publish_flow(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    engine = get_whatsapp_flows_engine()
    engine.client = client
    return await engine.publish_flow(arguments)


async def get_flow(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    engine = get_whatsapp_flows_engine()
    engine.client = client
    return await engine.get_flow(arguments)


async def list_flows(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    engine = get_whatsapp_flows_engine()
    engine.client = client
    return await engine.list_flows(arguments)


async def delete_flow(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    engine = get_whatsapp_flows_engine()
    engine.client = client
    return await engine.delete_flow(arguments)


async def deprecate_flow(client: MetaClient, arguments: Dict[str, Any]) -> ToolResult:
    engine = get_whatsapp_flows_engine()
    engine.client = client
    return await engine.deprecate_flow(arguments)


def get_tools(client: MetaClient) -> Dict[str, Tuple[mcp_types.Tool, ToolHandler]]:
    """Register WhatsApp Flows tools"""
    return {
        "meta.whatsapp.flows.create": (
            mcp_types.Tool(
                name="meta.whatsapp.flows.create",
                description="Create a WhatsApp Flow for lead generation, surveys, or interactive forms. Build structured conversations. Use for WhatsApp lead capture.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "waba_id": {"type": "string", "description": "WhatsApp Business Account ID"},
                        "name": {"type": "string", "description": "Flow name"},
                        "categories": {
                            "type": "array",
                            "items": {"type": "string", "enum": ["LEAD_GENERATION", "SIGN_UP", "BOOKING_APPOINTMENT", "CONTACT_US", "CUSTOMER_SUPPORT", "SURVEY", "OTHER"]}
                        },
                        "clone_flow_id": {"type": "string", "description": "Optional: Clone from existing flow"}
                    },
                    "required": ["waba_id", "name"]
                }
            ),
            partial(create_flow, client)
        ),
        "meta.whatsapp.flows.update_json": (
            mcp_types.Tool(
                name="meta.whatsapp.flows.update_json",
                description="Update WhatsApp Flow JSON with screens, forms, and navigation logic. Design multi-step conversations. Use for flow design.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "flow_id": {"type": "string"},
                        "flow_json": {"type": "object", "description": "Flow JSON with version and screens"}
                    },
                    "required": ["flow_id", "flow_json"]
                }
            ),
            partial(update_flow_json, client)
        ),
        "meta.whatsapp.flows.publish": (
            mcp_types.Tool(
                name="meta.whatsapp.flows.publish",
                description="Publish a WhatsApp Flow to make it live for users. Activate for production use. Use for flow deployment.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "flow_id": {"type": "string"}
                    },
                    "required": ["flow_id"]
                }
            ),
            partial(publish_flow, client)
        ),
        "meta.whatsapp.flows.get": (
            mcp_types.Tool(
                name="meta.whatsapp.flows.get",
                description="Get WhatsApp Flow details including status, validation errors, and JSON definition. View flow configuration. Use for flow inspection.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "flow_id": {"type": "string"}
                    },
                    "required": ["flow_id"]
                }
            ),
            partial(get_flow, client)
        ),
        "meta.whatsapp.flows.list": (
            mcp_types.Tool(
                name="meta.whatsapp.flows.list",
                description="List all WhatsApp Flows for a business account with status and categories. View flow inventory. Use for flow management.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "waba_id": {"type": "string", "description": "WhatsApp Business Account ID"}
                    },
                    "required": ["waba_id"]
                }
            ),
            partial(list_flows, client)
        ),
        "meta.whatsapp.flows.delete": (
            mcp_types.Tool(
                name="meta.whatsapp.flows.delete",
                description="Delete a draft WhatsApp Flow that hasn't been published. Remove unused flows. Use for flow cleanup.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "flow_id": {"type": "string"}
                    },
                    "required": ["flow_id"]
                }
            ),
            partial(delete_flow, client)
        ),
        "meta.whatsapp.flows.deprecate": (
            mcp_types.Tool(
                name="meta.whatsapp.flows.deprecate",
                description="Deprecate a published WhatsApp Flow to stop new uses while existing sessions continue. Phase out old flows. Use for flow retirement.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "flow_id": {"type": "string"}
                    },
                    "required": ["flow_id"]
                }
            ),
            partial(deprecate_flow, client)
        )
    }
