"""Alert management: list, create, and delete Metabase alerts.

Metabase v0.47+ replaced /api/alert with /api/notification.
Card alerts use payload_type "notification/card".
"""

from __future__ import annotations

from typing import Any

from metaverse.app import mcp
from metaverse.client import as_dict, as_list
from metaverse.client import get as api_get
from metaverse.client import post as api_post
from metaverse.client import put as api_put


@mcp.tool()
async def list_alerts() -> list[dict[str, Any]]:
    """List all active card alerts in Metabase.

    Returns [{id, card_id, card_name, send_condition, active}].
    """
    data = await api_get("/notification")
    return [
        {
            "id": a["id"],
            "card_id": (a.get("payload") or {}).get("card_id"),
            "card_name": ((a.get("payload") or {}).get("card") or {}).get("name", ""),
            "send_condition": (a.get("payload") or {}).get("send_condition", ""),
            "active": a.get("active", True),
        }
        for a in as_list(data)
        if a.get("payload_type") == "notification/card"
    ]


@mcp.tool()
async def create_alert(
    card_id: int,
    schedule_type: str = "daily",
    alert_condition: str = "rows",
) -> dict[str, Any]:
    """Create a Metabase alert on a saved question.

    Args:
        card_id: The question ID to monitor (from create_question or list_questions).
            The question should return the metric you want to watch.
        schedule_type: How often to check — "hourly", "daily", or "weekly".
            Note: scheduling is configured via notification handlers; omit for
            immediate/default scheduling.
        alert_condition: What triggers the alert:
            - "rows"       → alias for "has_result": alert when query returns rows
            - "has_result" → alert when query returns any rows
            - "goal_above" → alert when metric exceeds goal value on the card
            - "goal_below" → alert when metric falls below goal value on the card

    Returns {id, card_id, send_condition, active}.
    """
    # Normalise legacy "rows" alias
    send_condition = "has_result" if alert_condition == "rows" else alert_condition

    # Add the current user as the alert recipient
    me = as_dict(await api_get("/user/current"))
    user_id: int = me["id"]

    payload: dict[str, Any] = {
        "payload_type": "notification/card",
        "payload": {
            "card_id": card_id,
            "send_condition": send_condition,
        },
        "handlers": [
            {
                "channel_type": "channel/email",
                "recipients": [
                    {
                        "type": "notification-recipient/user",
                        "user_id": user_id,
                    }
                ],
            }
        ],
    }
    data = as_dict(await api_post("/notification", json=payload))
    return {
        "id": data["id"],
        "card_id": card_id,
        "send_condition": send_condition,
        "active": data.get("active", True),
    }


@mcp.tool()
async def delete_alert(alert_id: int) -> dict[str, Any]:
    """Deactivate (soft-delete) a card alert.

    Args:
        alert_id: The alert ID from list_alerts.

    Returns {deleted, alert_id}.
    """
    current = as_dict(await api_get(f"/notification/{alert_id}"))
    await api_put(
        f"/notification/{alert_id}",
        json={
            "id": alert_id,
            "active": False,
            "payload_type": current.get("payload_type"),
            "payload": current.get("payload"),
            "handlers": current.get("handlers", []),
        },
    )
    return {"deleted": True, "alert_id": alert_id}
