# Datetime utility functions
from datetime import datetime
from flask import current_app
from babel.dates import format_datetime
import pytz


def local_datetime_filter(dt):
    """将 UTC 时间转换为用户本地时区时间"""
    if dt is None:
        return ""
    
    # 获取用户时区配置
    user_tz_name = current_app.config.get('USER_TIMEZONE', 'UTC')
    try:
        user_tz = pytz.timezone(user_tz_name)
    except pytz.UnknownTimeZoneError:
        user_tz = pytz.utc
    
    # 如果时间没有时区信息，假设是 UTC
    if dt.tzinfo is None:
        dt = pytz.utc.localize(dt)
    
    # 转换到用户时区
    local_dt = dt.astimezone(user_tz)
    
    # 格式化输出
    return format_datetime(local_dt, format='medium', locale='en_US')
