"""Audit logging for security and actions."""

from datetime import datetime
from typing import Optional, Dict, Any
from sqlalchemy.orm import Session
from src.core.database import get_database, AuditLog
from src.core.logger import get_logger

logger = get_logger(__name__)


class AuditLogger:
    """Audit logging for security and important actions."""
    
    def __init__(self):
        """Initialize audit logger."""
        self.db = get_database()
    
    def log(
        self,
        action: str,
        entity_type: Optional[str] = None,
        entity_id: Optional[int] = None,
        details: Optional[Dict[str, Any]] = None
    ):
        """Log an audit event.
        
        Args:
            action: Action performed (e.g., "api_key_added", "order_placed")
            entity_type: Type of entity (e.g., "exchange", "strategy", "order")
            entity_id: ID of the entity
            details: Additional details as dictionary
        """
        session = self.db.get_session()
        try:
            audit_entry = AuditLog(
                action=action,
                entity_type=entity_type,
                entity_id=entity_id,
                details=details or {},
                timestamp=datetime.utcnow()
            )
            session.add(audit_entry)
            session.commit()
            
            # Also log to application logger
            logger.info(f"Audit: {action} on {entity_type} {entity_id}")
        except Exception as e:
            session.rollback()
            logger.error(f"Failed to log audit event: {e}")
        finally:
            session.close()
    
    def get_audit_log(
        self,
        entity_type: Optional[str] = None,
        entity_id: Optional[int] = None,
        limit: int = 100
    ) -> list[AuditLog]:
        """Get audit log entries.
        
        Args:
            entity_type: Filter by entity type
            entity_id: Filter by entity ID
            limit: Maximum number of entries to return
            
        Returns:
            List of AuditLog entries
        """
        session = self.db.get_session()
        try:
            query = session.query(AuditLog)
            
            if entity_type:
                query = query.filter_by(entity_type=entity_type)
            if entity_id:
                query = query.filter_by(entity_id=entity_id)
            
            return query.order_by(AuditLog.timestamp.desc()).limit(limit).all()
        finally:
            session.close()


# Global audit logger
_audit_logger: Optional[AuditLogger] = None


def get_audit_logger() -> AuditLogger:
    """Get global audit logger instance."""
    global _audit_logger
    if _audit_logger is None:
        _audit_logger = AuditLogger()
    return _audit_logger

