import { Injectable, Logger } from '@nestjs/common';
import { FeatureFlagService } from '../config/feature-flag.service';

/**
 * M-AI-04-05: Active Recall Execution Router
 *
 * 根据 ACTIVE_RECALL_ENGINE_MODE Feature Flag 决定执行分支：
 *   - 'legacy'  → 原有 AiAnalysisService 路径
 *   - 'unified' → AiJobCreationService → Unified Job Engine
 *
 * 设计约束（ADR-003）：
 *   - 分支判断集中在 Router，不散落在 Controller/Service/Worker
 *   - 支持用户白名单
 *   - 默认 legacy（Feature Flag 不存在或 disabled 时）
 */

const FLAG_NAME = 'ACTIVE_RECALL_ENGINE_MODE';

@Injectable()
export class ActiveRecallExecutionRouter {
  private readonly logger = new Logger(ActiveRecallExecutionRouter.name);

  constructor(private readonly featureFlag: FeatureFlagService) {}

  /**
   * 判断是否应使用 Unified 引擎。
   *
   * @param userId - 请求用户 ID（用于白名单检查）
   * @returns true → unified 路径, false → legacy 路径
   */
  async shouldUseUnified(userId: string): Promise<boolean> {
    try {
      const enabled = await this.featureFlag.isEnabled(FLAG_NAME, userId);
      this.logger.log(
        `ACTIVE_RECALL_ENGINE_MODE=${enabled ? 'unified' : 'legacy'} for userId=${userId}`,
      );
      return enabled;
    } catch (err: any) {
      // FeatureFlag 查询失败 → 安全回退到 legacy
      this.logger.warn(
        `FeatureFlag query failed, falling back to legacy: ${err.message}`,
      );
      return false;
    }
  }
}
