"""Content/creative management tools for Influ2 MCP."""

from __future__ import annotations

import json
from typing import Annotated, Literal

from influ2_mcp.client import get_api_client
from influ2_mcp.config import resolve_client_id
from influ2_mcp.errors import Influ2Error, format_error_for_llm
from influ2_mcp.server import mcp


@mcp.tool()
async def influ2_list_contents(
    scope: Annotated[
        Literal["by_cohort", "by_id", "mappings"],
        "What to retrieve:\n"
        "- 'by_cohort': List all content/ads attached to a cohort (requires cohort_id)\n"
        "- 'by_id': Get full details of one specific content (requires content_id)\n"
        "- 'mappings': Get content-to-asset mappings showing which images/videos "
        "are used in each creative",
    ],
    cohort_id: Annotated[
        str | None,
        "Required when scope='by_cohort'. The cohort to list contents for.",
    ] = None,
    content_id: Annotated[
        str | None,
        "Required when scope='by_id'. The specific content/creative ID.",
    ] = None,
    client_id: Annotated[
        str | None,
        "Influ2 client ID. Omit to use configured default.",
    ] = None,
    content_type: Annotated[
        str | None,
        "Filter by type: 'video' or 'images'. Only for scope='by_cohort'.",
    ] = None,
    content_status: Annotated[
        str | None,
        "Filter by status: 'active', 'paused', or 'archived'. Only for scope='by_cohort'.",
    ] = None,
    limit: Annotated[int, "Max results for mappings (1-100, default 50)"] = 50,
    offset: Annotated[int, "Pagination offset for mappings (default 0)"] = 0,
) -> str:
    """List and inspect ad creatives/content in Influ2.

    Content items are the actual advertisements shown to targets — they combine
    uploaded images/videos with ad copy (title, description, primary text) and
    a landing page URL. Formats include social (single-image, carousel, video),
    native, and display banners.

    Content goes through moderation: awaiting_moderation → on_moderation → approved/declined.

    When a user asks: "What ads are running in this campaign?", "Show me the creatives",
    "What's the status of my content?", "Which assets are used in which ads?",
    "List active/paused content", "Show me the ad details",
    "Is my content approved or still in moderation?"
    """
    try:
        cid = resolve_client_id(client_id)
        api_client = get_api_client()

        if scope == "by_cohort":
            if not cohort_id:
                return json.dumps({
                    "error": True,
                    "message": "cohort_id is required when scope='by_cohort'.",
                    "suggestion": "Use influ2_list_cohorts to find cohort IDs.",
                })

            params: dict = {}
            if content_type:
                params["type"] = content_type
            if content_status:
                params["status"] = content_status

            response = await api_client.get(
                f"/public/v1/clients/{cid}/cohorts/{cohort_id}/contents",
                params=params if params else None,
            )
            return json.dumps({
                "contents": response if isinstance(response, list) else response.get("data", response),
                "_next_steps": [
                    "Get full details for a specific content with "
                    "influ2_list_contents(scope='by_id', content_id='...')",
                ],
            }, indent=2, default=str)

        elif scope == "by_id":
            if not content_id:
                return json.dumps({
                    "error": True,
                    "message": "content_id is required when scope='by_id'.",
                    "suggestion": (
                        "Use influ2_list_contents(scope='by_cohort', cohort_id='...') "
                        "to find content IDs."
                    ),
                })

            response = await api_client.get(
                f"/public/v1/clients/{cid}/contents/{content_id}"
            )
            return json.dumps({"content": response}, indent=2, default=str)

        elif scope == "mappings":
            params = {"limit": min(max(limit, 1), 100), "offset": max(offset, 0)}
            response = await api_client.get(
                f"/public/v1/clients/{cid}/contents/mappings",
                params=params,
            )
            return json.dumps({
                "mappings": response.get("data", response),
                "paging": response.get("paging", {}),
            }, indent=2, default=str)

        else:
            return json.dumps({
                "error": True,
                "message": f"Invalid scope '{scope}'. Must be 'by_cohort', 'by_id', or 'mappings'.",
            })

    except Influ2Error as e:
        return json.dumps(format_error_for_llm(e))
    except Exception as e:
        return json.dumps(format_error_for_llm(e))


