import time
from datetime import datetime
from typing import Dict, Type, Any

class IDMan:

    def __init__(self):
        self.last_time = 0
        self.sequence = 0
    
    def next_id(self) -> int:
        now = int(time.time() * 1000)  # 当前毫秒时间戳
        
        # 如果时间戳相同，增加序列号
        if now == self.last_time:
            self.sequence += 1
        else:
            # 时间戳不同，重置序列号
            self.last_time = now
            self.sequence = 0
        
        # 组合ID：时间戳左移4位 + 序列号
        id = (now << 4) | self.sequence
        return id

def explain_id(id_value: int) -> str:
    # 提取时间戳和序列号
    timestamp = id_value >> 4
    sequence = id_value & 0xF  # 获取低4位
    
    # 转换时间戳为可读格式
    dt = datetime.fromtimestamp(timestamp / 1000)  # 转换为秒
    time_str = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]  # 保留毫秒
    
    return f"ID: {id_value} (时间: {time_str}, 序列号: {sequence})"

class IDTag:

    def __init__(self, get_tag_func):
        self.get_tag_func = get_tag_func

    def __str__(self):
        return f"{self.get_tag_func()}"

class IDClass:
    id_man = IDMan()  # 类成员，只初始化一次
    
    def __init__(self, get_tag_func=None):
        self.id = self.id_man.next_id()
        self.base_tag = f"{self.__class__.__name__}/{self.id}"
        if hasattr(self, "_get_tag"):
            self.tag = IDTag(self._get_tag)
        else:
            self.tag = self.base_tag
    
    def explain_id(self):
        return explain_id(self.id)