from django.http import JsonResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.conf import settings
import json
import logging
from datetime import datetime
from elasticsearch import Elasticsearch

# Initialize logger
logger = logging.getLogger(__name__)

# Initialize Elasticsearch client (will be configured in settings)
def get_elasticsearch_client():
    return Elasticsearch(
        cloud_id=settings.ELASTICSEARCH_CLOUD_ID,
        api_key=settings.ELASTICSEARCH_API_KEY,
        request_timeout=30,
        retry_on_timeout=True
    )

@csrf_exempt
@require_http_methods(["POST"])
def livehelpnow_webhook(request):
    """
    Webhook endpoint to receive LiveHelpNow events and index them to Elasticsearch
    """
    try:
        # Parse JSON payload
        payload = json.loads(request.body.decode('utf-8'))
        
        # Add processing metadata
        payload['@timestamp'] = datetime.utcnow().isoformat()
        payload['processed_at'] = datetime.now().isoformat()
        payload['source'] = 'livehelpnow_webhook'
        
        # Validate required fields (customize based on your needs)
        if not payload.get('event_type'):
            logger.warning("Received payload without event_type")
            return JsonResponse({
                'status': 'error', 
                'message': 'Missing event_type in payload'
            }, status=400)
        
        # Create time-based index name
        index_name = f"livehelpnow-{datetime.utcnow().strftime('%Y-%m')}"
        
        # Get Elasticsearch client
        es = get_elasticsearch_client()
        
        # Index document to Elasticsearch
        response = es.index(
            index=index_name,
            body=payload
        )
        
        # Log successful indexing
        logger.info(f"Successfully indexed LiveHelpNow event: {payload.get('event_type')} to {index_name}")
        
        return JsonResponse({
            'status': 'success',
            'indexed': True,
            'index': index_name,
            'document_id': response.get('_id'),
            'result': response.get('result')
        })
        
    except json.JSONDecodeError as e:
        logger.error(f"Invalid JSON in webhook payload: {e}")
        return JsonResponse({
            'status': 'error',
            'message': 'Invalid JSON format'
        }, status=400)
        
    except Exception as e:
        logger.error(f"Error processing LiveHelpNow webhook: {str(e)}")
        return JsonResponse({
            'status': 'error',
            'message': 'Internal server error',
            'details': str(e) if settings.DEBUG else None
        }, status=500)

@csrf_exempt
@require_http_methods(["GET"])
def webhook_health_check(request):
    """
    Health check endpoint for the webhook
    """
    try:
        es = get_elasticsearch_client()
        
        # Test Elasticsearch connection
        if es.ping():
            return JsonResponse({
                'status': 'healthy',
                'elasticsearch': 'connected',
                'timestamp': datetime.utcnow().isoformat()
            })
        else:
            return JsonResponse({
                'status': 'unhealthy',
                'elasticsearch': 'disconnected'
            }, status=503)
            
    except Exception as e:
        return JsonResponse({
            'status': 'unhealthy',
            'error': str(e)
        }, status=503)
