from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.contrib import messages
from .models import AIChatHistory, AIConfiguration, SyncHistoryLog
from .ai_service import sync_ai_history

def index(request):
    if request.user.is_authenticated:
        return redirect('dashboard')
    return render(request, 'core/index.html')

@login_required
def dashboard(request):
    profile = request.user.profile
    company = profile.company
    
    query = request.GET.get('q', '')
    histories = AIChatHistory.objects.filter(company=company)
    
    if query:
        histories = histories.filter(
            Q(chat_title__icontains=query) | 
            Q(chat_content__icontains=query)
        )
    
    # Ordering is now handled by Model Meta
    histories = histories.order_by('-chat_last_date')
    
    # AI Configurations for the company
    ai_configs = AIConfiguration.objects.filter(company=company)
    last_sync_log = SyncHistoryLog.objects.filter(company=company).order_by('-timestamp').first()
    
    context = {
        'histories': histories,
        'query': query,
        'ai_configs': ai_configs,
        'last_sync_log': last_sync_log,
    }
    return render(request, 'core/dashboard.html', context)

@login_required
def chat_detail(request, pk):
    profile = request.user.profile
    chat = get_object_or_404(AIChatHistory, pk=pk, company=profile.company)
    return render(request, 'core/chat_detail.html', {'chat': chat})

@login_required
def sync_history(request):
    if request.method == 'POST':
        profile = request.user.profile
        configs = AIConfiguration.objects.filter(company=profile.company, is_active=True)
        
        if not configs.exists():
            messages.warning(request, "No active AI configurations found. Please contact your administrator to add an API key.")
        else:
            total_synced = 0
            for config in configs:
                sync_ai_history(config)
                # Re-fetch the log we just created
                latest_log = SyncHistoryLog.objects.filter(configuration=config).order_by('-timestamp').first()
                if latest_log and latest_log.status == 'success':
                    total_synced += latest_log.records_synced
            
            if total_synced > 0:
                messages.success(request, f"Successfully synced {total_synced} new chat records.")
            else:
                messages.info(request, "Sync completed. No new records found.")
                
    return redirect('dashboard')
