# -*- coding: utf-8 -*-
"""数据类型解析器"""
from datetime import datetime
from decimal import Decimal, ROUND_HALF_UP
from dateutil import parser as dtparser
from zoneinfo import ZoneInfo

class TypeParser:
    """类型解析工具"""
    
    @staticmethod
    def parse_timestamp(s: str, tz: ZoneInfo) -> datetime | None:
        """解析时间戳"""
        if not s:
            return None
        try:
            dt = dtparser.parse(s)
            if dt.tzinfo is None:
                return dt.replace(tzinfo=tz)
            return dt.astimezone(tz)
        except Exception:
            return None
    
    @staticmethod
    def parse_decimal(value, scale: int = 2) -> Decimal | None:
        """解析金额"""
        if value is None:
            return None
        try:
            d = Decimal(str(value))
            return d.quantize(Decimal(10) ** -scale, rounding=ROUND_HALF_UP)
        except Exception:
            return None
    
    @staticmethod
    def parse_int(value) -> int | None:
        """解析整数"""
        if value is None:
            return None
        try:
            return int(value)
        except Exception:
            return None
    
    @staticmethod
    def format_timestamp(dt: datetime | None, tz: ZoneInfo) -> str | None:
        """格式化时间戳"""
        if not dt:
            return None
        return dt.astimezone(tz).strftime("%Y-%m-%d %H:%M:%S")
