import { logger } from '../utils/logger';
import { FeatureGovernanceService } from '../core/governance/FeatureGovernanceService';
import { RedisService } from '../utils/RedisService';

export interface CrawlerState {
  targetDomain: string;
  successRate: number;
  avgLatency: number;
  currentDelay: number;
  proxyStrategy: 'ROTATING' | 'RESIDENTIAL' | 'STICKY';
  riskLevel: 'LOW' | 'MEDIUM' | 'HIGH';
}

/**
 * [CORE_AUTO_06] 基于强化学习的爬虫策略优化 (RL-Crawler)
 * @description 核心逻辑：自动学习绕过风控的最佳路径。基于历史响应状态动态调整并发、延迟与代理策略。
 */
export class RLCrawlerService {
  private static readonly REDIS_PREFIX = 'rl_crawler:state:';

  /**
   * 获取并优化下一次请求的策略
   */
  static async getOptimizedStrategy(domain: string, tenantId?: string): Promise<CrawlerState> {
    // Feature Flag Check
    if (!(await FeatureGovernanceService.isEnabled('CORE_AUTO_RL_CRAWLER', tenantId))) {
      return {
        targetDomain: domain,
        successRate: 1.0,
        avgLatency: 200,
        currentDelay: 1000,
        proxyStrategy: 'ROTATING',
        riskLevel: 'LOW'
      };
    }

    const stateKey = `${this.REDIS_PREFIX}${domain}`;
    const cachedState = await RedisService.get(stateKey);
    let state: CrawlerState;

    if (cachedState) {
      state = JSON.parse(cachedState);
    } else {
      state = {
        targetDomain: domain,
        successRate: 0.95,
        avgLatency: 500,
        currentDelay: 2000,
        proxyStrategy: 'ROTATING',
        riskLevel: 'LOW'
      };
    }

    // 强化学习决策逻辑 (RL Decision Logic)
    // 1. 如果成功率下降，增加延迟，升级代理
    if (state.successRate < 0.8) {
      state.currentDelay *= 1.5;
      state.proxyStrategy = 'RESIDENTIAL';
      state.riskLevel = 'HIGH';
    } 
    // 2. 如果成功率极高且延迟大，尝试缩减延迟以提升效率
    else if (state.successRate > 0.98 && state.currentDelay > 500) {
      state.currentDelay *= 0.8;
      state.riskLevel = 'LOW';
    }

    await RedisService.set(stateKey, JSON.stringify(state), 3600); // 缓存1小时
    logger.info(`[RL-Crawler] Optimized strategy for ${domain}: Delay=${state.currentDelay}ms, Strategy=${state.proxyStrategy}`);
    
    return state;
  }

  /**
   * 反馈请求结果 (Learning Feedback)
   */
  static async reportResult(domain: string, success: boolean, latency: number) {
    const stateKey = `${this.REDIS_PREFIX}${domain}`;
    const cachedState = await RedisService.get(stateKey);
    if (!cachedState) return;

    const state: CrawlerState = JSON.parse(cachedState);
    
    // 简单的指数移动平均更新成功率与延迟 (EMA Update)
    const alpha = 0.1;
    state.successRate = (1 - alpha) * state.successRate + alpha * (success ? 1 : 0);
    state.avgLatency = (1 - alpha) * state.avgLatency + alpha * latency;

    await RedisService.set(stateKey, JSON.stringify(state), 3600);
    logger.debug(`[RL-Crawler] Feedback updated for ${domain}: SuccessRate=${state.successRate.toFixed(4)}`);
  }
}
