from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
import json
from django.conf import settings
from twilio.rest import Client
import logging

logger = logging.getLogger(__name__)

@csrf_exempt
@api_view(['POST'])
@permission_classes([AllowAny])
def twilio_webhook(request):
    """
    Webhook endpoint for receiving WhatsApp messages from Twilio.
    """
    try:
        # Twilio sends data as form-urlencoded
        from_number = request.POST.get('From', '')
        body = request.POST.get('Body', '')
        
        logger.info(f"Received WhatsApp message from {from_number}: {body}")
        
        # We will dispatch the incoming message to our bot state machine.
        # But first, we still must return an empty TwiML response to Twilio
        # to acknowledge receipt, because our bot uses the REST API (send_reply) to respond asynchronously.
        from twilio.twiml.messaging_response import MessagingResponse
        from .bot import process_whatsapp_message
        
        # Process the message
        process_whatsapp_message(from_number, body)
        
        response = MessagingResponse()
        return HttpResponse(str(response), content_type='text/xml')
        
    except Exception as e:
        logger.error(f"Error processing webhook: {str(e)}")
        return HttpResponse("Error", status=400)


@csrf_exempt
@api_view(['POST'])
@permission_classes([AllowAny]) # Allows testing without auth first
def send_whatsapp_message(request):
    """
    API endpoint to send custom codes via WhatsApp.
    Expects JSON: {"to": "+1234567890", "message": "Your custom code is X."}
    """
    try:
        data = json.loads(request.body)
        to_number = data.get('to')
        message_body = data.get('message')
        
        if not to_number or not message_body:
            return JsonResponse({'error': 'Missing "to" or "message" fields'}, status=400)
            
        account_sid = settings.TWILIO_ACCOUNT_SID
        auth_token = settings.TWILIO_AUTH_TOKEN
        from_number = settings.TWILIO_FROM_NUMBER
        
        if not account_sid or not auth_token:
            return JsonResponse({'error': 'Twilio credentials not configured in .env'}, status=500)
            
        client = Client(account_sid, auth_token)
        
        # Format numbers correctly for WhatsApp
        if not to_number.startswith('whatsapp:'):
            if not to_number.startswith('+'):
                to_number = f"+{to_number}"
            to_number = f"whatsapp:{to_number}"
            
        if not from_number.startswith('whatsapp:'):
            if not from_number.startswith('+'):
                from_number = f"+{from_number}"
            from_number = f"whatsapp:{from_number}"
            
        message = client.messages.create(
            from_=from_number,
            body=message_body,
            to=to_number
        )
        
        return JsonResponse({
            'status': 'success',
            'message_sid': message.sid,
            'body': message_body
        })
        
    except Exception as e:
        logger.error(f"Error sending WhatsApp message: {str(e)}")
        return JsonResponse({'error': str(e)}, status=500)
