import json
from flask_login import current_user
from sqlalchemy import event
from sqlalchemy.orm import Session
from sqlalchemy.orm.attributes import get_history
from app.core.models.base import BaseModel
from app.core.models.audit import AuditLog
from app.extensions import db

def get_user_id():
    try:
        if current_user and current_user.is_authenticated:
            return str(current_user.id)
    except:
        pass
    return None

class AuditService:
    """
    Service for handling audit logging.
    Now primarily powered by automatic SQLAlchemy event listeners.
    """

    @staticmethod
    def log(entity, action, old_data=None, new_data=None):
        """
        Legacy manual method. Supported for backward compatibility.
        If a user manually calls this, we inject a marker so the automatic
        listener knows not to double-log this exact action.
        """
        if not hasattr(entity, '_manual_audit_handled'):
            entity._manual_audit_handled = True
            
        user_id = get_user_id()

        def serialize(data):
            if data is None: return None
            if isinstance(data, (dict, list)): return json.dumps(data, default=str)
            return str(data)

        # Store explicit changes if provided manually
        changes_json = None
        if action == 'UPDATE' and old_data and new_data:
            changes = {}
            for k, v in new_data.items():
                if k in old_data and old_data[k] != v:
                    changes[k] = {'old': old_data[k], 'new': v}
                elif k not in old_data:
                    changes[k] = {'old': None, 'new': v}
            # Special check for manual manager overrides passed via dict
            if new_data.get('_manager_override'):
                changes['_manager_override'] = True
            if changes:
                changes_json = json.dumps(changes, default=str)

        log_entry = AuditLog(
            entity_type=entity.__class__.__name__,
            entity_id=str(entity.id),
            action=action,
            old_value=serialize(old_data),
            new_value=serialize(new_data),
            changes=changes_json,
            created_by=user_id
        )

        db.session.add(log_entry)
        db.session.commit()

# --- Automatic Audit Logging via SQLAlchemy Events ---

@event.listens_for(Session, 'before_flush')
def receive_before_flush(session, flush_context, instances):
    user_id = get_user_id()
    
    # Process Insertions
    for obj in session.new:
        if isinstance(obj, BaseModel) and not isinstance(obj, AuditLog):
            if getattr(obj, '_manual_audit_handled', False): continue
            
            new_val = {c.name: getattr(obj, c.name) for c in obj.__table__.columns}
            log = AuditLog(
                entity_type=obj.__class__.__name__,
                entity_id=str(obj.id),
                action='CREATE',
                new_value=json.dumps(new_val, default=str),
                created_by=user_id
            )
            session.add(log)
            
    # Process Updates
    for obj in session.dirty:
        if session.is_modified(obj) and isinstance(obj, BaseModel) and not isinstance(obj, AuditLog):
            if getattr(obj, '_manual_audit_handled', False): continue
            
            old_val = {}
            new_val = {}
            changes = {}
            
            for c in obj.__table__.columns:
                # Exclude uninteresting columns from detailed diff
                if c.name in ['updated_at', 'updated_by', 'version_id']:
                    continue
                    
                history = get_history(obj, c.name)
                if history.has_changes():
                    old_c = history.deleted[0] if history.deleted else None
                    new_c = history.added[0] if history.added else None
                    changes[c.name] = {'old': old_c, 'new': new_c}
                    old_val[c.name] = old_c
                    new_val[c.name] = new_c
                else:
                    val = getattr(obj, c.name)
                    old_val[c.name] = val
                    new_val[c.name] = val
                    
            if changes:
                # Include explicit flag if the user forced an override property
                if hasattr(obj, '_manager_override') and obj._manager_override:
                    changes['_manager_override'] = True
                    
                log = AuditLog(
                    entity_type=obj.__class__.__name__,
                    entity_id=str(obj.id),
                    action='UPDATE',
                    old_value=json.dumps(old_val, default=str),
                    new_value=json.dumps(new_val, default=str),
                    changes=json.dumps(changes, default=str),
                    created_by=user_id
                )
                session.add(log)
                
    # Process Deletions
    for obj in session.deleted:
        if isinstance(obj, BaseModel) and not isinstance(obj, AuditLog):
            if getattr(obj, '_manual_audit_handled', False): continue
            
            old_val = {c.name: getattr(obj, c.name) for c in obj.__table__.columns}
            log = AuditLog(
                entity_type=obj.__class__.__name__,
                entity_id=str(obj.id),
                action='DELETE',
                old_value=json.dumps(old_val, default=str),
                created_by=user_id
            )
            session.add(log)
