from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework import status

from apps.agents.models import AgentConfig, AgentVoiceConfig, AgentGuardrail, AgentSystemTool


@api_view(["GET"])
@permission_classes([AllowAny])
def agent_list(request):
    """List available agent names (for discovery)."""
    names = list(AgentConfig.objects.values_list("name", flat=True))
    return Response({"agents": names})


@api_view(["GET"])
@permission_classes([AllowAny])
def agent_config(request, agent_name):
    """Worker fetches full config for an agent by name."""
    try:
        agent = AgentConfig.objects.prefetch_related(
            "voice_config", "guardrails", "system_tools", "knowledge_base"
        ).get(name=agent_name)
    except AgentConfig.DoesNotExist:
        return Response({"error": "Agent not found"}, status=status.HTTP_404_NOT_FOUND)

    voice = getattr(agent, "voice_config", None)
    data = {
        "id": agent.pk,
        "name": agent.name,
        "stt_provider": agent.stt_provider,
        "tts_provider": agent.tts_provider,
        "llm_provider": agent.llm_provider,
        "llm_model": agent.llm_model,
        "system_prompt": agent.system_prompt,
        "default_language": agent.default_language,
        "first_message_inbound": agent.first_message_inbound,
        "first_message_outbound": agent.first_message_outbound,
        "knowledge_base_id": str(agent.knowledge_base_id) if agent.knowledge_base_id else None,
        "voice": {
            "voice_id": voice.voice_id if voice else None,
            "tts_model_family": voice.tts_model_family if voice else None,
            "similarity": voice.similarity if voice else None,
            "speed": voice.speed if voice else None,
            "stability": voice.stability if voice else None,
            "output_format": voice.output_format if voice else None,
        } if voice else {},
        "guardrails": [g.guardrail_key for g in agent.guardrails.filter(enabled=True)],
        "system_tools": [t.tool_key for t in agent.system_tools.filter(enabled=True)],
    }
    return Response(data)
