import { Injectable, Logger } from '@nestjs/common';
import type { AiProvider } from './providers/provider.interface';
import { createProvider } from './providers/factory';
import { AiConfigService } from '../config/ai-config.service';

/**
 * AI Gateway — 屏蔽底层 Provider，对上层 AiService 提供统一 callTool 接口
 * 激活的 Provider 切换 / Key 改变时自动重建客户端
 */
@Injectable()
export class AiGatewayService {
  private readonly logger = new Logger(AiGatewayService.name);
  private cachedProvider: AiProvider | null = null;
  private cachedKey: string = '';

  constructor(private readonly config: AiConfigService) {}

  async getActiveProvider(): Promise<AiProvider> {
    const cfg = await this.config.getActiveProvider();
    if (!cfg) {
      throw new Error('未配置任何 AI 提供商，请在「AI 配置」页面新增并激活一个');
    }
    const sig = `${cfg.format}:${cfg.baseURL}:${cfg.apiKey}`;
    if (!this.cachedProvider || this.cachedKey !== sig) {
      this.cachedProvider = createProvider(cfg);
      this.cachedKey = sig;
      this.logger.log(`Provider 切换到 ${cfg.name} (${cfg.format})`);
    }
    return this.cachedProvider;
  }

  async getActiveModel(): Promise<string> {
    const cfg = await this.config.getActiveProvider();
    if (!cfg) throw new Error('未配置任何 AI 提供商');
    return cfg.model;
  }
}
