import logging
from flask import session, request
from psycopg2.extras import Json
from db import get_db_connection, get_db_cursor
from utils.network import get_client_ip

logger = logging.getLogger(__name__)


def log_audit(action, entity_type, entity_id=None, old_values=None, new_values=None, additional_info=None):
    """Log changes to the audit log"""
    with get_db_connection() as conn:
        with get_db_cursor(conn) as cur:
            try:
                username = session.get('username', 'system')
                ip_address = get_client_ip() if request else None
                user_agent = request.headers.get('User-Agent') if request else None
                
                # Debug logging
                logger.info(f"Audit log - IP address captured: {ip_address}, Action: {action}, User: {username}")
                
                # Convert dictionaries to JSONB
                old_json = Json(old_values) if old_values else None
                new_json = Json(new_values) if new_values else None
                
                cur.execute("""
                    INSERT INTO audit_log 
                    (username, action, entity_type, entity_id, old_values, new_values, 
                     ip_address, user_agent, additional_info)
                    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
                """, (username, action, entity_type, entity_id, old_json, new_json, 
                      ip_address, user_agent, Json(additional_info) if isinstance(additional_info, dict) else additional_info))
                
                conn.commit()
            except Exception as e:
                logger.error(f"Audit log error: {e}")
                conn.rollback()