import os
import platform
from functools import wraps
from django import get_version as django_version
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.contrib import messages
from .models import Project, PipelineStep, CgiAsset, StudioConfig

def studio_admin_required(view_func):
    """Decorator to restrict access to studio admin only."""
    @wraps(view_func)
    def _wrapped_view(request, *args, **kwargs):
        if not request.session.get('is_studio_admin', False):
            messages.warning(request, "Acesso restrito. Por favor, insira sua chave de administrador.")
            return redirect('admin_login')
        return view_func(request, *args, **kwargs)
    return _wrapped_view

def home(request):
    """Render the CGI Studio Command Center."""
    # Ensure StudioConfig exists and generate key if needed
    config, created = StudioConfig.objects.get_or_create(id=1)
    if created or not config.admin_access_key:
        config.save() # Triggers uuid generation
    
    projects = Project.objects.prefetch_related('steps').all()
    
    total_projects = projects.count()
    active_productions = projects.filter(status='PROD').count()
    completed_projects = projects.filter(status='DONE').count()

    context = {
        "projects": projects,
        "total_projects": total_projects,
        "active_productions": active_productions,
        "completed_projects": completed_projects,
        "current_time": timezone.now(),
        "is_admin": request.session.get('is_studio_admin', False),
    }
    return render(request, "core/index.html", context)

def admin_login(request):
    """View to enter the unique admin access key."""
    if request.method == "POST":
        key = request.POST.get("access_key")
        try:
            config = StudioConfig.objects.get(id=1)
            if key == config.admin_access_key:
                request.session['is_studio_admin'] = True
                messages.success(request, "Bem-vindo, Comandante do Estúdio!")
                return redirect('home')
            else:
                messages.error(request, "Chave de acesso inválida.")
        except StudioConfig.DoesNotExist:
            messages.error(request, "Configuração do estúdio não encontrada.")
            
    return render(request, "core/admin_login.html")

def admin_logout(request):
    """Logout the studio admin."""
    request.session['is_studio_admin'] = False
    return redirect('home')

@studio_admin_required
def asset_library(request):
    """View all digital assets (Characters, Props, Environments)."""
    assets = CgiAsset.objects.select_related('project').all()
    asset_types = {
        'CHAR': assets.filter(asset_type='CHAR'),
        'PROP': assets.filter(asset_type='PROP'),
        'ENV': assets.filter(asset_type='ENV'),
    }
    
    context = {
        "assets": assets,
        "asset_types": asset_types,
    }
    return render(request, "core/asset_library.html", context)

def project_detail(request, slug):
    """Render the detailed pipeline for a specific production."""
    project = get_object_or_404(Project.objects.prefetch_related('steps', 'assets'), slug=slug)
    
    context = {
        "project": project,
        "steps": project.steps.all(),
        "assets": project.assets.all(),
    }
    return render(request, "core/project_detail.html", context)
