"""Helpers para añadir filtros a dashboards de Metabase."""

import uuid as _uuid

from .client import MetabaseClient
from .metabase_update_dashboard_safe import metabase_update_dashboard_safe


def metabase_add_dashboard_filter(
    client: MetabaseClient,
    dashboard_id: int,
    name: str,
    slug: str,
    filter_type: str,
    card_mappings: list[dict],
    *,
    default: str | None = None,
) -> dict:
    """Añade un filtro a un dashboard y lo conecta a las cards indicadas.

    Crea un parametro a nivel de dashboard y actualiza los parameter_mappings
    de cada dashcard indicada. Usa metabase_update_dashboard_safe internamente.

    Args:
        client: Cliente autenticado.
        dashboard_id: ID del dashboard.
        name: Nombre visible del filtro (ej: "Fecha desde").
        slug: Slug URL-friendly (ej: "fecha_desde").
        filter_type: Tipo del filtro. Comunes: "string/=", "number/=",
            "date/single", "date/range", "date/relative", "category".
        card_mappings: Lista de dicts con la conexión filtro→card. Formato:
            [{"card_id": 42, "template_tag": "fecha_desde"}, ...]
            Cada dict indica qué card y qué template-tag SQL debe recibir el valor.
        default: Valor por defecto del filtro (opcional).

    Returns:
        Dict con resultado de metabase_update_dashboard_safe.

    Example:
        >>> result = metabase_add_dashboard_filter(
        ...     client, 887, "Fecha desde", "fecha_desde", "string/=",
        ...     [{"card_id": 7711, "template_tag": "fecha_desde"},
        ...      {"card_id": 7719, "template_tag": "fecha_desde"}],
        ... )
    """
    from .dashboards import metabase_get_dashboard

    # 1. Leer dashboard actual
    dash = metabase_get_dashboard(client, dashboard_id)
    current_params = dash.get("parameters", [])
    current_dashcards = dash.get("dashcards", [])

    # 2. Crear el parameter
    param_id = _uuid.uuid4().hex[:8]
    new_param = {
        "id": param_id,
        "type": filter_type,
        "name": name,
        "slug": slug,
    }
    if default is not None:
        new_param["default"] = default

    updated_params = current_params + [new_param]

    # 3. Build card_id → template_tag mapping
    tag_by_card = {m["card_id"]: m["template_tag"] for m in card_mappings}

    # 4. Update dashcards with parameter_mappings
    updated_dashcards = []
    for dc in current_dashcards:
        dc_card_id = dc.get("card_id")
        if dc_card_id in tag_by_card:
            mappings = list(dc.get("parameter_mappings", []))
            mappings.append({
                "parameter_id": param_id,
                "card_id": dc_card_id,
                "target": ["variable", ["template-tag", tag_by_card[dc_card_id]]],
            })
            dc_copy = {**dc, "parameter_mappings": mappings}
            updated_dashcards.append(dc_copy)
        else:
            updated_dashcards.append(dc)

    # 5. Update via safe function
    return metabase_update_dashboard_safe(
        client, dashboard_id,
        dashcards_update=updated_dashcards,
        extra_fields={"parameters": updated_params},
    )
