"""
Views for LLM Manager — FBVs per Red Panda Standards.

Rewrites Spelunker's CBVs (LLMApiListView, LLMModelListView, LLMUsageListView)
as function-based views.
"""

from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db.models import Count, Sum
from django.shortcuts import get_object_or_404, redirect, render

from .forms import LLMApiForm, LLMModelForm
from .models import LLMApi, LLMModel, LLMUsage
from .services import test_llm_api


@login_required
def dashboard(request):
    """LLM Manager dashboard with overview statistics."""
    totals = LLMUsage.objects.filter(user=request.user).aggregate(
        total_input=Sum("input_tokens"),
        total_output=Sum("output_tokens"),
        total_cost=Sum("total_cost"),
        count=Count("id"),
    )
    context = {
        "api_count": LLMApi.objects.filter(is_active=True).count(),
        "model_count": LLMModel.objects.filter(is_active=True).count(),
        "usage_count": totals["count"] or 0,
        "total_input_tokens": totals["total_input"] or 0,
        "total_output_tokens": totals["total_output"] or 0,
        "total_cost": totals["total_cost"] or 0,
        "recent_usage": (
            LLMUsage.objects.filter(user=request.user)
            .select_related("model", "model__api")
            .order_by("-timestamp")[:10]
        ),
        "active_apis": LLMApi.objects.filter(is_active=True),
        "system_embedding_model": LLMModel.get_system_embedding_model(),
        "system_chat_model": LLMModel.get_system_chat_model(),
        "system_reranker_model": LLMModel.get_system_reranker_model(),
    }
    return render(request, "llm_manager/dashboard.html", context)


# --------------------------------------------------------------------------- #
# LLMApi CRUD
# --------------------------------------------------------------------------- #


@login_required
def api_list(request):
    """List all LLM APIs."""
    apis = LLMApi.objects.all().order_by("name")
    return render(request, "llm_manager/api_list.html", {"apis": apis})


@login_required
def api_create(request):
    """Create a new LLM API."""
    if request.method == "POST":
        form = LLMApiForm(request.POST)
        if form.is_valid():
            api = form.save(commit=False)
            api.created_by = request.user
            api.save()
            messages.success(request, f"API '{api.name}' created.")
            return redirect("llm_manager:api_detail", pk=api.pk)
    else:
        form = LLMApiForm()
    return render(request, "llm_manager/api_form.html", {"form": form, "is_edit": False})


@login_required
def api_detail(request, pk):
    """View LLM API details with associated models."""
    api = get_object_or_404(LLMApi, pk=pk)
    models = api.models.all().order_by("name")
    return render(request, "llm_manager/api_detail.html", {"api": api, "models": models})


@login_required
def api_edit(request, pk):
    """Edit an LLM API."""
    api = get_object_or_404(LLMApi, pk=pk)
    if request.method == "POST":
        form = LLMApiForm(request.POST, instance=api)
        if form.is_valid():
            form.save()
            messages.success(request, f"API '{api.name}' updated.")
            return redirect("llm_manager:api_detail", pk=api.pk)
    else:
        form = LLMApiForm(instance=api)
    return render(request, "llm_manager/api_form.html", {"form": form, "api": api, "is_edit": True})


@login_required
def api_delete(request, pk):
    """Delete an LLM API."""
    api = get_object_or_404(LLMApi, pk=pk)
    if request.method == "POST":
        name = api.name
        api.delete()
        messages.success(request, f"API '{name}' deleted.")
        return redirect("llm_manager:api_list")
    return render(request, "llm_manager/api_confirm_delete.html", {"api": api})


@login_required
def api_test(request, pk):
    """Test an LLM API connection and discover models."""
    api = get_object_or_404(LLMApi, pk=pk)
    if request.method == "POST":
        result = test_llm_api(api)
        if result["success"]:
            messages.success(request, f"API test successful: {result['message']}")
        else:
            messages.error(request, f"API test failed: {result['error']}")
    return redirect("llm_manager:api_detail", pk=api.pk)


# --------------------------------------------------------------------------- #
# LLMModel views
# --------------------------------------------------------------------------- #


@login_required
def model_list(request):
    """List all LLM Models, optionally filtered by API."""
    qs = LLMModel.objects.select_related("api").order_by("api__name", "name")
    api_id = request.GET.get("api")
    if api_id:
        qs = qs.filter(api_id=api_id)
    apis = LLMApi.objects.all().order_by("name")
    return render(request, "llm_manager/model_list.html", {"models": qs, "apis": apis, "selected_api": api_id})


@login_required
def model_create(request):
    """Create a new LLM Model."""
    if request.method == "POST":
        form = LLMModelForm(request.POST)
        if form.is_valid():
            model = form.save()
            messages.success(request, f"Model '{model.name}' created.")
            return redirect("llm_manager:model_list")
    else:
        form = LLMModelForm()
        api_id = request.GET.get("api")
        if api_id:
            form.initial["api"] = api_id
    return render(request, "llm_manager/model_form.html", {"form": form, "is_edit": False})


@login_required
def model_detail(request, pk):
    """View LLM Model details."""
    model = get_object_or_404(LLMModel.objects.select_related("api"), pk=pk)
    return render(request, "llm_manager/model_detail.html", {"model": model})


@login_required
def model_edit(request, pk):
    """Edit an LLM Model."""
    model = get_object_or_404(LLMModel, pk=pk)
    if request.method == "POST":
        form = LLMModelForm(request.POST, instance=model)
        if form.is_valid():
            form.save()
            messages.success(request, f"Model '{model.name}' updated.")
            return redirect("llm_manager:model_detail", pk=model.pk)
    else:
        form = LLMModelForm(instance=model)
    return render(request, "llm_manager/model_form.html", {"form": form, "model": model, "is_edit": True})


@login_required
def model_delete(request, pk):
    """Delete an LLM Model."""
    model = get_object_or_404(LLMModel, pk=pk)
    if request.method == "POST":
        name = model.name
        model.delete()
        messages.success(request, f"Model '{name}' deleted.")
        return redirect("llm_manager:model_list")
    return render(request, "llm_manager/model_confirm_delete.html", {"model": model})


# --------------------------------------------------------------------------- #
# Usage views
# --------------------------------------------------------------------------- #


@login_required
def usage_list(request):
    """List LLM usage history for the current user."""
    qs = (
        LLMUsage.objects.filter(user=request.user)
        .select_related("model", "model__api")
        .order_by("-timestamp")
    )
    totals = qs.aggregate(
        total_input=Sum("input_tokens"),
        total_output=Sum("output_tokens"),
        total_cached=Sum("cached_tokens"),
        total_cost=Sum("total_cost"),
    )
    return render(request, "llm_manager/usage_list.html", {"usage_records": qs[:100], "totals": totals})
