from sqlalchemy.types import TypeDecorator, DateTime
from datetime import datetime, timezone

class UTCDateTime(TypeDecorator):
    impl = DateTime
    cache_ok = True

    def process_bind_param(self, value, dialect):
        # 入库（你前面已经在用，但这里一起兜底）
        if value is None:
            return None
        if isinstance(value, str):
            value = datetime.fromisoformat(value)
        if value.tzinfo:
            value = value.astimezone(timezone.utc).replace(tzinfo=None)
        return value

    def process_result_value(self, value, dialect):
        # 出库：统一变成 UTC aware
        if value is None:
            return None
        return value.replace(tzinfo=timezone.utc)
