import queue
import threading
import time
import logging
from django.db import transaction
from .models import OperationLog

logger = logging.getLogger(__name__)

# Queue for storing log entries
log_queue = queue.Queue()
BATCH_SIZE = 100
FLUSH_INTERVAL = 5  # seconds

def log_worker():
    """
    Background worker to process logs from the queue.
    """
    buffer = []
    last_flush = time.time()
    
    while True:
        try:
            # Block for a short time to allow accumulation
            entry = log_queue.get(timeout=1)
            buffer.append(entry)
        except queue.Empty:
            pass

        current_time = time.time()
        
        # Flush if buffer is full or time interval exceeded
        if len(buffer) >= BATCH_SIZE or (buffer and current_time - last_flush >= FLUSH_INTERVAL):
            _flush_logs(buffer)
            buffer = []
            last_flush = current_time

def _flush_logs(buffer):
    """
    Bulk create logs in the database.
    """
    try:
        # Avoid circular import issues during startup
        # if the model is not ready yet
        
        logs = []
        for item in buffer:
            logs.append(OperationLog(**item))
            
        OperationLog.objects.bulk_create(logs)
        # logger.info(f"Flushed {len(logs)} logs to database.")
    except Exception as e:
        logger.error(f"Error flushing logs to database: {e}")

def start_worker():
    """
    Start the background thread.
    """
    t = threading.Thread(target=log_worker, daemon=True)
    t.start()
    return t

def enqueue_log(**kwargs):
    """
    Add a log entry to the queue.
    """
    log_queue.put(kwargs)
