from django.shortcuts import render, redirect, get_object_or_404
from django.http import JsonResponse
from django.views.decorators.http import require_POST
import json
from .models import Article, TodoItem, Conversation, Message
from .forms import TodoItemForm
import time
from ai.local_ai_api import LocalAIApi

def index(request):
    if request.method == 'POST':
        form = TodoItemForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        form = TodoItemForm()
    
    todo_list = TodoItem.objects.all().order_by('-created_at')
    articles = Article.objects.all()
    
    context = {
        'articles': articles,
        'todo_list': todo_list,
        'form': form,
        'timestamp': int(time.time()),
    }
    return render(request, "core/index.html", context)

def kanban_board(request):
    tasks = TodoItem.objects.all().order_by('created_at')
    tasks_by_status = {
        status_value: list(filter(lambda t: t.status == status_value, tasks))
        for status_value, status_display in TodoItem.STATUS_CHOICES
    }

    context = {
        'tasks_by_status': tasks_by_status,
        'status_choices': TodoItem.STATUS_CHOICES,
        'timestamp': int(time.time()),
    }
    return render(request, "core/kanban.html", context)

def article_detail(request, article_id):
    article = Article.objects.get(pk=article_id)
    return render(request, "core/article_detail.html", {"article": article})

@require_POST
def update_task_status(request):
    try:
        data = json.loads(request.body)
        task_id = data.get('task_id')
        new_status = data.get('new_status')

        task = get_object_or_404(TodoItem, id=task_id)
        task.status = new_status
        task.save()

        return JsonResponse({'success': True})
    except (json.JSONDecodeError, TypeError, ValueError) as e:
        return JsonResponse({'success': False, 'error': str(e)}, status=400)

def chat_view(request, conversation_id=None):
    if request.method == 'POST':
        if 'title' in request.POST:
            title = request.POST.get('title', 'New Conversation')
            conversation = Conversation.objects.create(title=title)
            return redirect('core:chat_detail', conversation_id=conversation.id)
        
        elif 'text' in request.POST and conversation_id:
            text = request.POST.get('text')
            selected_conversation = get_object_or_404(Conversation, id=conversation_id)
            if text:
                Message.objects.create(conversation=selected_conversation, text=text, sender_type='user')
                
                try:
                    response = LocalAIApi.create_response({
                        "input": [
                            {"role": "system", "content": "You are a helpful assistant."},
                            {"role": "user", "content": text}
                        ]
                    })
                    ai_text = LocalAIApi.extract_text(response)
                    if not ai_text:
                        ai_text = "I couldn't process that. Please try again."
                except Exception as e:
                    ai_text = f"An error occurred: {str(e)}"

                Message.objects.create(conversation=selected_conversation, text=ai_text, sender_type='ai')

            return redirect('core:chat_detail', conversation_id=selected_conversation.id)

    conversations = Conversation.objects.order_by('-created_at')
    selected_conversation = None
    if conversation_id:
        selected_conversation = get_object_or_404(Conversation, id=conversation_id)

    return render(request, 'core/chat.html', {
        'conversation_list': conversations,
        'selected_conversation': selected_conversation,
        'timestamp': int(time.time()),
    })
