import time
import logging
import datetime
from django.db import connections
from django.utils import timezone
from .context import TrackerContext
from .models import OperationLog
from .queue import enqueue_log

logger = logging.getLogger(__name__)

def install_db_logger():
    """
    Install database query logger wrapper for all connections.
    """
    for alias in connections:
        conn = connections[alias]
        if hasattr(conn, 'execute_wrappers'): 
            # Check if already installed to avoid duplicates
            if sql_logger_wrapper not in conn.execute_wrappers:
                conn.execute_wrappers.append(sql_logger_wrapper)

def sql_logger_wrapper(execute, sql, params, many, context):
    start = time.time()
    try:
        return execute(sql, params, many, context)
    finally:
        duration = (time.time() - start) * 1000
        
        # Filter out own logs to avoid recursion and infinite loops
        if 'django_ops_logger_operationlog' in sql:
            return

        trace_id = TrackerContext.get_trace_id()
        if not trace_id:
            # Optionally log DB queries even without request context (e.g. management commands)
            # But we need a trace_id to group them.
            return 

        details = {
            'sql': sql,
            'params': str(params)[:1000], # Truncate large params
            'many': many,
            'database': context['connection'].alias if context else 'default'
        }

        enqueue_log(
            trace_id=trace_id,
            operation_type=OperationLog.OpType.DB,
            level='DEBUG',
            start_time=timezone.now() - datetime.timedelta(milliseconds=duration), 
            end_time=timezone.now(),
            duration=duration,
            user_id=TrackerContext.get_user_id(),
            username=TrackerContext.get_username(),
            details=details,
        )
