import json
import logging
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Message, BotSettings
from ai.local_ai_api import LocalAIApi

logger = logging.getLogger(__name__)

def index(request):
    messages = Message.objects.all().order_by('-timestamp')[:50]
    settings = BotSettings.objects.first()
    if not settings:
        settings = BotSettings.objects.create()
    
    context = {
        'messages': messages,
        'settings': settings,
    }
    return render(request, 'core/index.html', context)

def settings_view(request):
    settings = BotSettings.objects.first()
    if not settings:
        settings = BotSettings.objects.create()
    
    if request.method == 'POST':
        settings.system_prompt = request.POST.get('system_prompt', settings.system_prompt)
        settings.is_active = 'is_active' in request.POST
        settings.verify_token = request.POST.get('verify_token', settings.verify_token)
        settings.save()
        return redirect('index')
    
    return render(request, 'core/settings.html', {'settings': settings})

@csrf_exempt
def webhook(request):
    if request.method == 'GET':
        # Meta Webhook verification
        mode = request.GET.get('hub.mode')
        token = request.GET.get('hub.verify_token')
        challenge = request.GET.get('hub.challenge')
        
        settings = BotSettings.objects.first()
        verify_token = settings.verify_token if settings else "my_secure_token_123"
        
        if mode and token:
            if mode == 'subscribe' and token == verify_token:
                logger.info("WEBHOOK_VERIFIED")
                return HttpResponse(challenge)
            else:
                return HttpResponse('Verification failed', status=403)
        return HttpResponse('Verification failed', status=403)

    elif request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            logger.info(f"Incoming WhatsApp data: {json.dumps(data)}")
            
            # Check if it's a message from WhatsApp
            if 'object' in data and data['object'] == 'whatsapp_business_account':
                for entry in data['entry']:
                    for change in entry['changes']:
                        value = change['value']
                        if 'messages' in value:
                            for msg in value['messages']:
                                sender_number = msg['from']
                                message_body = msg.get('text', {}).get('body', '')
                                
                                if message_body:
                                    process_whatsapp_message(sender_number, message_body)
                                    
            return JsonResponse({'status': 'ok'})
        except Exception as e:
            logger.error(f"Error processing webhook: {str(e)}")
            return JsonResponse({'status': 'error', 'message': str(e)}, status=500)

def process_whatsapp_message(sender_number, message_body):
    settings = BotSettings.objects.first()
    if not settings or not settings.is_active:
        return

    # Store incoming message
    db_msg = Message.objects.create(
        sender_number=sender_number,
        message_in=message_body
    )

    # Call Gemini via AI Proxy
    prompt_input = [
        {"role": "system", "content": settings.system_prompt},
        {"role": "user", "content": message_body},
    ]
    
    try:
        response = LocalAIApi.create_response({
            "input": prompt_input,
            "model": "gemini-1.5-flash", # Explicitly request gemini-1.5-flash
        })
        
        if response.get("success"):
            ai_text = LocalAIApi.extract_text(response)
            db_msg.message_out = ai_text
            db_msg.save()
            
            # NOTE: In a real app, you'd call Meta API here to send db_msg.message_out back to sender_number.
            # For this task, we focus on the integration and dashboard as requested.
            logger.info(f"Gemini response for {sender_number}: {ai_text}")
        else:
            logger.error(f"AI Proxy Error: {response.get('error')}")
    except Exception as e:
        logger.error(f"Error calling Gemini: {str(e)}")