"""Client management tools for Influ2 MCP."""

from __future__ import annotations

import json
from typing import Annotated

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


@mcp.tool()
async def influ2_list_clients() -> str:
    """List all Influ2 clients (advertising accounts) accessible with the current API key.

    Returns client IDs, names, and basic metadata. Use this FIRST if no client_id
    is configured, because every other tool requires a client_id. If only one client
    is returned, use that client_id for subsequent calls.

    When a user asks: "What clients do I have?", "Show me my accounts",
    "Which account should I use for my campaign?", "What is my client ID?"
    """
    try:
        client = get_api_client()
        response = await client.get("/public/v1/clients")

        clients = response.get("clients", [])
        config = get_config()

        result = {
            "clients": [
                {"id": c.get("id"), "name": c.get("name")}
                for c in clients
            ],
            "total_count": len(clients),
        }

        if config.client_id:
            result["_note"] = (
                f"Default client_id is configured: {config.client_id}. "
                "Other tools will use this automatically."
            )
        elif len(clients) == 1:
            result["_note"] = (
                f"Only one client found. Use client_id='{clients[0].get('id')}' "
                "for all subsequent tool calls."
            )
        else:
            result["_next_steps"] = [
                "Pick a client_id from the list above and pass it to other tools.",
                "Or set INFLU2_CLIENT_ID environment variable to skip this step.",
            ]

        return json.dumps(result, indent=2)

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


@mcp.tool()
async def influ2_create_client(
    name: Annotated[str, "Name for the new client/account (1-255 characters)"],
    website: Annotated[str, "Client website URL (up to 2048 characters)"],
    user_emails: Annotated[
        str | None,
        "Optional JSON array of email addresses to grant access (up to 100). "
        "Example: '[\"user@company.com\", \"admin@company.com\"]'"
    ] = None,
) -> str:
    """Create a new Influ2 client (advertising account) and optionally grant user access.

    Requires an admin API key. Creates a new dashboard and optionally invites users.

    When a user asks: "Create a new client", "Set up an account for [company]",
    "Onboard [company] to Influ2", "Provision a new dashboard"
    """
    try:
        api_client = get_api_client()

        body: dict = {"name": name, "website": website}
        if user_emails:
            emails = json.loads(user_emails)
            body["users"] = [{"email": e} for e in emails]

        response = await api_client.post("/public/v1/clients", json=body)

        result = {
            "client": response,
            "_next_steps": [
                f"Use client_id='{response.get('id')}' for subsequent tool calls.",
                "Create cohorts with influ2_create_cohort to start campaigns.",
            ],
        }
        return json.dumps(result, indent=2)

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