"""Action type discovery API routes."""

from fastapi import APIRouter, Depends, HTTPException

from notify_bridge_core.providers.actions import (
    get_action_type,
    get_action_types,
    get_all_action_types,
)
from notify_bridge_core.providers.capabilities import get_all_capabilities

from ..auth.dependencies import get_current_user
from ..database.models import User

router = APIRouter(prefix="/api/action-types", tags=["action-types"])


@router.get("")
async def list_all_action_types(
    user: User = Depends(get_current_user),
):
    """All action types grouped by provider."""
    all_types = get_all_action_types()
    result: dict[str, list[dict]] = {}
    for provider_type, defns in all_types.items():
        result[provider_type] = [
            {
                "key": d.key,
                "provider_type": d.provider_type,
                "display_name": d.display_name,
                "description": d.description,
            }
            for d in defns
        ]
    # Also include providers with no action types (from capabilities)
    all_caps = get_all_capabilities()
    for ptype in all_caps:
        if ptype not in result:
            result[ptype] = []
    return result


@router.get("/{provider_type}")
async def list_provider_action_types(
    provider_type: str,
    user: User = Depends(get_current_user),
):
    """Action types for a specific provider."""
    defns = get_action_types(provider_type)
    return [
        {
            "key": d.key,
            "provider_type": d.provider_type,
            "display_name": d.display_name,
            "description": d.description,
        }
        for d in defns
    ]


@router.get("/{provider_type}/{key}/schema")
async def get_action_type_schema(
    provider_type: str,
    key: str,
    user: User = Depends(get_current_user),
):
    """Get rule and config JSON schemas for an action type."""
    defn = get_action_type(provider_type, key)
    if not defn:
        raise HTTPException(status_code=404, detail="Action type not found")
    return {
        "key": defn.key,
        "provider_type": defn.provider_type,
        "display_name": defn.display_name,
        "description": defn.description,
        "rule_schema": defn.rule_schema,
        "config_schema": defn.config_schema,
    }
