"""
Mnemosyne project-level views — landing page and dashboard.
"""

from django.contrib.auth.decorators import login_required
from django.core.cache import cache
from django.db import connection
from django.http import JsonResponse
from django.shortcuts import render

from llm_manager.models import LLMApi, LLMModel


def landing(request):
    """
    Public landing page. Redirects authenticated users to dashboard.
    """
    if request.user.is_authenticated:
        return dashboard(request)
    return render(request, "mnemosyne/landing.html")


@login_required
def dashboard(request):
    """
    Authenticated user dashboard — overview of all Mnemosyne features.
    """
    context = {
        "api_count": LLMApi.objects.filter(is_active=True).count(),
        "model_count": LLMModel.objects.filter(is_active=True).count(),
        "system_embedding": LLMModel.get_system_embedding_model(),
        "system_chat": LLMModel.get_system_chat_model(),
    }

    # Try to get library counts (Neo4j may be unavailable)
    try:
        from library.utils import neo4j_available

        if neo4j_available():
            from library.models import Library

            context["library_count"] = len(Library.nodes.all())
        else:
            context["library_count"] = None
    except Exception:
        context["library_count"] = None

    return render(request, "mnemosyne/dashboard.html", context)


def live(request):
    return JsonResponse({"status": "ok"})


def ready(request):
    errors = {}
    try:
        connection.ensure_connection()
    except Exception as e:
        errors["db"] = str(e)
    try:
        cache.get("__readiness_probe__")
    except Exception as e:
        errors["cache"] = str(e)
    if errors:
        return JsonResponse({"status": "error", "errors": errors}, status=503)
    return JsonResponse({"status": "ok"})
