from django.shortcuts import render, redirect, get_object_or_404
from .models import Task
from .forms import TaskForm
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from ai.local_ai_api import LocalAIApi
import json

def assistant_chat(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            message = data.get('message')

            if not message:
                return JsonResponse({'error': 'No message provided'}, status=400)

            # Call the Local AI API
            response = LocalAIApi.create_response(
                {
                    "input": [
                        {"role": "system", "content": "You are a helpful assistant named Roma."},
                        {"role": "user", "content": message},
                    ],
                }
            )

            if response.get("success"):
                ai_reply = LocalAIApi.extract_text(response)
                if not ai_reply:
                    decoded = LocalAIApi.decode_json_from_response(response)
                    ai_reply = json.dumps(decoded, ensure_ascii=False) if decoded else str(response.get("data", ""))
                return JsonResponse({'reply': ai_reply})
            else:
                return JsonResponse({'error': response.get("error", "Unknown AI error")}, status=500)

        except json.JSONDecodeError:
            return JsonResponse({'error': 'Invalid JSON'}, status=400)
    
    return JsonResponse({'error': 'Only POST method is allowed'}, status=405)

def index(request):
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        form = TaskForm()

    # Prepara una struttura dati nidificata per il template
    tasks_by_status_cat = {status[0]: {cat[0]: [] for cat in Task.CATEGORY_CHOICES} for status in Task.STATUS_CHOICES}
    all_tasks = Task.objects.all()

    for task in all_tasks:
        tasks_by_status_cat[task.status][task.category].append(task)

    context = {
        'form': form,
        'tasks': tasks_by_status_cat,
        'categories': Task.CATEGORY_CHOICES,
        'statuses': Task.STATUS_CHOICES,
    }
    return render(request, 'core/index.html', context)

def task_edit(request, pk):
    task = get_object_or_404(Task, pk=pk)
    if request.method == 'POST':
        form = TaskForm(request.POST, instance=task)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        form = TaskForm(instance=task)
    return render(request, 'core/task_edit.html', {'form': form, 'task': task})

def task_delete(request, pk):
    task = get_object_or_404(Task, pk=pk)
    task.delete()
    return redirect('index')

def task_set_status_completato(request, pk):
    task = get_object_or_404(Task, pk=pk)
    task.status = 'COMPLETATO'
    task.save()
    return redirect('index')

def task_set_status_in_sospeso(request, pk):
    task = get_object_or_404(Task, pk=pk)
    task.status = 'IN_SOSPESO'
    task.save()
    return redirect('index')

def task_set_status_da_fare(request, pk):
    task = get_object_or_404(Task, pk=pk)
    task.status = 'DA_FARE'
    task.save()
    return redirect('index')
