"""
Yahoo Finance API请求频率限制器 - 简化版

防止429错误的基本限制器
"""

import time
import logging
from typing import Dict, Any

logger = logging.getLogger(__name__)


class YahooFinanceRateLimiter:
    """简化版Yahoo Finance限制器"""
    
    def __init__(self):
        self.last_request_time = 0
        self.min_interval = 3  # 3秒间隔
        self.success_count = 0
        self.failure_count = 0
    
    def wait_if_needed(self) -> Dict[str, Any]:
        """等待以避免超限"""
        current_time = time.time()
        time_since_last = current_time - self.last_request_time
        
        if time_since_last < self.min_interval:
            wait_time = self.min_interval - time_since_last
            logger.debug(f"Yahoo Finance限制器等待 {wait_time:.2f} 秒")
            time.sleep(wait_time)
        
        self.last_request_time = time.time()
        return {"status": "ready", "waited": time_since_last < self.min_interval}
    
    def record_success(self):
        """记录成功请求"""
        self.success_count += 1
    
    def record_failure(self):
        """记录失败请求"""
        self.failure_count += 1
    
    def get_stats(self) -> Dict[str, Any]:
        """获取统计信息"""
        total = self.success_count + self.failure_count
        return {
            "success_count": self.success_count,
            "failure_count": self.failure_count,
            "total_requests": total,
            "success_rate": self.success_count / total if total > 0 else 0
        }


class AlphaVantageRateLimiter:
    """简化版Alpha Vantage限制器"""
    
    def __init__(self):
        self.daily_count = 0
        self.daily_limit = 450
        self.last_reset = time.time()
    
    def can_make_request(self) -> bool:
        """检查是否可以发起请求"""
        # 每天重置计数
        current_time = time.time()
        if current_time - self.last_reset > 86400:  # 24小时
            self.daily_count = 0
            self.last_reset = current_time
        
        return self.daily_count < self.daily_limit
    
    def record_request(self):
        """记录请求"""
        self.daily_count += 1
    
    def get_stats(self) -> Dict[str, Any]:
        """获取统计信息"""
        return {
            "daily_count": self.daily_count,
            "daily_limit": self.daily_limit,
            "remaining": max(0, self.daily_limit - self.daily_count)
        }


# 全局实例
yahoo_limiter = YahooFinanceRateLimiter()
alpha_vantage_limiter = AlphaVantageRateLimiter()


def get_yahoo_limiter() -> YahooFinanceRateLimiter:
    """获取Yahoo Finance限制器实例"""
    return yahoo_limiter


def get_alpha_vantage_limiter() -> AlphaVantageRateLimiter:
    """获取Alpha Vantage限制器实例"""
    return alpha_vantage_limiter


def get_limiter_status() -> Dict[str, Any]:
    """获取所有限制器状态"""
    return {
        "yahoo_finance": yahoo_limiter.get_stats(),
        "alpha_vantage": alpha_vantage_limiter.get_stats()
    } 