import json
from django.shortcuts import render, redirect, get_object_or_404
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from .models import Project, Script, MediaAsset
from ai.local_ai_api import LocalAIApi

def index(request):
    projects = Project.objects.all().order_by('-created_at')
    return render(request, 'core/index.html', {
        'projects': projects,
        'title': 'Creator Studio Dashboard',
    })

@require_POST
def create_project(request):
    title = request.POST.get('title', 'Untitled Project')
    description = request.POST.get('description', '')
    project = Project.objects.create(title=title, description=description)
    return redirect('project_detail', project_id=project.id)

def project_detail(request, project_id):
    project = get_object_or_404(Project, id=project_id)
    scripts = project.scripts.all().order_by('-created_at')
    assets = project.assets.all().order_by('-created_at')
    return render(request, 'core/project_detail.html', {
        'project': project,
        'scripts': scripts,
        'assets': assets,
        'title': f'Studio: {project.title}',
    })

@require_POST
def generate_script(request, project_id):
    project = get_object_or_404(Project, id=project_id)
    prompt = request.POST.get('prompt', '')
    
    if not prompt:
        return JsonResponse({'success': False, 'error': 'Prompt is required'})
    
    # Construct a high-quality AI prompt for video scripting
    ai_input = [
        {"role": "system", "content": "You are an expert social media content creator and scriptwriter for TikTok, Reels, and YouTube Shorts. Generate a catchy script with Scene details, Action, and Dialogue/Narration."},
        {"role": "user", "content": f"Generate a short-form video script for the following idea: {prompt}"}
    ]
    
    response = LocalAIApi.create_response({
        "input": ai_input,
    })
    
    if response.get("success"):
        content = LocalAIApi.extract_text(response)
        script = Script.objects.create(
            project=project,
            prompt=prompt,
            content=content
        )
        return JsonResponse({
            'success': True, 
            'content': content,
            'script_id': script.id,
            'created_at': script.created_at.strftime('%Y-%m-%d %H:%M')
        })
    else:
        return JsonResponse({
            'success': False, 
            'error': response.get('message', 'AI Generation failed')
        })