import redis
import time
import logging
from typing import Optional

logger = logging.getLogger(__name__)

class DistributedLock:
    def __init__(self, redis_client: redis.Redis, lock_name: str, expire_time: int = 60):
        """
        初始化分布式锁
        
        Args:
            redis_client: Redis客户端实例
            lock_name: 锁的名称
            expire_time: 锁的过期时间（秒）
        """
        self.redis_client = redis_client
        self.lock_name = f"lock:{lock_name}"
        self.expire_time = expire_time
        
    def acquire(self) -> bool:
        """
        尝试获取锁
        
        Returns:
            bool: 是否成功获取锁
        """
        try:
            # 使用SETNX命令尝试获取锁
            # 如果key不存在，则设置key的值为当前时间戳，并设置过期时间
            current_time = int(time.time())
            result = self.redis_client.set(
                self.lock_name,
                current_time,
                ex=self.expire_time,
                nx=True
            )
            
            if result:
                logger.info(f"成功获取锁: {self.lock_name}")
                return True
            else:
                logger.info(f"未能获取锁: {self.lock_name}")
                return False
                
        except Exception as e:
            logger.error(f"获取锁时发生错误: {e}")
            return False
            
    def release(self) -> bool:
        """
        释放锁
        
        Returns:
            bool: 是否成功释放锁
        """
        try:
            # 先检查锁是否存在
            lock_value = self.redis_client.get(self.lock_name)
            if not lock_value:
                logger.info(f"锁不存在: {self.lock_name}")
                return True
                
            # 删除锁
            result = self.redis_client.delete(self.lock_name)
            if result:
                logger.info(f"成功释放锁: {self.lock_name}, 原值: {lock_value}")
                return True
            else:
                logger.warning(f"释放锁失败: {self.lock_name}, 原值: {lock_value}")
                return False
                
        except Exception as e:
            logger.error(f"释放锁时发生错误: {e}")
            return False 