import os
import platform
from django.shortcuts import render, redirect
from django.utils import timezone
from .utils import get_all_services_status
from .models import ServiceSetting
from .api_clients import JellyfinClient, RadarrClient, SonarrClient, JellyseerrClient

def home(request):
    """Render the dashboard with service statuses and detailed info."""
    service_status = get_all_services_status()
    
    # Fetch additional data for the dashboard
    jellyfin = JellyfinClient()
    recent_media = jellyfin.get_recent_items(6)
    
    radarr = RadarrClient()
    radarr_queue = radarr.get_queue()
    
    sonarr = SonarrClient()
    sonarr_queue = sonarr.get_queue()
    
    jellyseerr = JellyseerrClient()
    pending_requests = jellyseerr.get_requests(5)
    
    # Add URLs to the context for links
    settings = {s.name: s.url for s in ServiceSetting.objects.all()}
    for service in service_status:
        service_status[service]['url'] = settings.get(service, '')
    
    context = {
        "project_name": "Matzeflix Dashboard",
        "service_status": service_status,
        "recent_media": recent_media,
        "radarr_queue_count": len(radarr_queue),
        "sonarr_queue_count": len(sonarr_queue),
        "pending_requests": pending_requests,
        "current_time": timezone.now(),
        "jellyfin_url": settings.get('jellyfin', ''),
    }
    return render(request, "core/index.html", context)

def settings_view(request):
    """View to manage service settings."""
    services = ['jellyfin', 'radarr', 'sonarr', 'jellyseerr']
    
    if request.method == "POST":
        for service in services:
            url = request.POST.get(f"{service}_url")
            api_key = request.POST.get(f"{service}_api_key")
            is_active = request.POST.get(f"{service}_active") == "on"
            
            setting, created = ServiceSetting.objects.get_or_create(name=service)
            setting.url = url or ""
            setting.api_key = api_key or ""
            setting.is_active = is_active
            setting.save()
        return redirect('home')

    settings_query = ServiceSetting.objects.all()
    settings_dict = {s.name: s for s in settings_query}
    
    service_configs = []
    for service in services:
        config = settings_dict.get(service)
        if not config:
            config = {'name': service, 'url': '', 'api_key': '', 'is_active': False}
        service_configs.append(config)
    
    context = {
        "service_configs": service_configs,
    }
    return render(request, "core/settings.html", context)
