#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Xiang Wang <ramwin@qq.com>

import time
from typing import Union

from .types import RedisClient

class UniqueId:
    """
    generated by ai: https://www.kimi.com/chat/19ab06e4-1232-8061-8000-0905a428a309
    """
    def __init__(self, client: RedisClient, klass: str, timeout: float = 3600) -> None:
        self._r = client
        self._klass = klass
        self._timeout = timeout
        self._auto_key = f"{klass}:auto"
    def _id_key(self, key: str) -> str:
        return f"{self._klass}:id:{key}"
    def get_or_create(self, key: str) -> int:
        id_key = self._id_key(key)
        while True:
            existing = self._r.get(id_key)
            if existing is not None:
                return int(existing)
            new_id = self._r.incr(self._auto_key)
            ok = self._r.set(id_key, new_id, nx=True, ex=int(self._timeout))
            if ok:
                return new_id
