"""
审计日志记录模块

用法：
  from .audit_logger import audit_log
  audit_log(action="create_user", user=current_user, details={...}, request=request, db=db)
"""

from sqlalchemy.orm import Session
from ..models import AuditLog
from typing import Optional, Dict, Any
from datetime import datetime


def audit_log(
    action: str,
    *,
    user=None,  # User 对象或 None
    username: Optional[str] = None,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    details: Optional[Dict[str, Any]] = None,
    ip_address: Optional[str] = None,
    user_agent: Optional[str] = None,
    db: Session = None
) -> None:
    """
    记录审计日志

    参数：
      action: 操作类型（必填），如 "login", "create_user", "delete_user", "publish"
      user: 操作用户的 User 对象（可选，如果提供则自动填充 user_id 和 username）
      username: 直接指定用户名（如果 user 为 None 则必须提供）
      resource_type: 资源类型，如 "user", "topic", "publish_record"
      resource_id: 资源ID
      details: 操作详情字典（如变更前后的值）
      ip_address: IP 地址
      user_agent: User-Agent
      db: 数据库会话（必填）
    """
    if db is None:
        raise ValueError("db session is required")

    # 确定 user_id 和 username
    user_id = None
    if user is not None:
        user_id = getattr(user, 'id', None)
        username = getattr(user, 'username', username)
    if not username:
        username = "anonymous"

    log = AuditLog(
        user_id=user_id,
        username=username,
        action=action,
        resource_type=resource_type,
        resource_id=resource_id,
        details=details or {},
        ip_address=ip_address,
        user_agent=user_agent,
        created_at=datetime.utcnow()
    )
    db.add(log)
    db.commit()
    # 不抛出异常，避免影响主流程
