import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createDeepSeek, type DeepSeekProvider } from '@ai-sdk/deepseek';
import { createGoogleGenerativeAI, type GoogleGenerativeAIProvider } from '@ai-sdk/google';
import type { LanguageModel } from 'ai';
import type { AppConfig } from '../../../config/configuration';

/**
 * AiProviderService — 模型工厂。
 *
 * harness 原则:AiCall 只声明 modelId 字符串,provider 决定怎么实例化。
 * 这里集中处理 vendor 路由(deepseek / gemini;以后加 qwen 时本类内部扩 switch)。
 *
 * 设计选择:
 *   - DeepSeek 走官方 SDK @ai-sdk/deepseek(国内 endpoint,合规)
 *   - Gemini 走 @ai-sdk/google(generativelanguage.googleapis.com;海外需可达,可设 baseURL 走代理)
 *   - 不走 Vercel AI Gateway(美国基建,数据出境)
 *   - modelId 字符串直传,不硬编码 enum;前端可只传逻辑键 "deepseek" / "gemini",
 *     由本类解析到 config 配的具体型号(单一真源在后端 env)
 */
@Injectable()
export class AiProviderService {
  private readonly logger = new Logger(AiProviderService.name);
  private readonly deepseek: DeepSeekProvider;
  private readonly google: GoogleGenerativeAIProvider;
  private readonly defaultModel: string;
  private readonly geminiDefaultModel: string;

  constructor(private readonly config: ConfigService<AppConfig, true>) {
    const ai = this.config.get('ai', { infer: true });
    this.defaultModel = ai.defaultModel;
    this.geminiDefaultModel = ai.geminiDefaultModel;

    if (!ai.deepseekApiKey) {
      this.logger.warn(
        'DEEPSEEK_API_KEY 未设置 — DeepSeek 调用会失败。开发环境到 https://platform.deepseek.com/api_keys 申请',
      );
    }
    this.deepseek = createDeepSeek({ apiKey: ai.deepseekApiKey, baseURL: ai.deepseekBaseUrl });

    if (!ai.geminiApiKey) {
      this.logger.warn('GEMINI_API_KEY 未设置 — Gemini 调用会失败。到 https://aistudio.google.com/apikey 申请');
    }
    this.google = createGoogleGenerativeAI({
      apiKey: ai.geminiApiKey,
      // baseURL 留空 → SDK 默认 endpoint;设了走代理 / 镜像
      ...(ai.geminiBaseUrl ? { baseURL: ai.geminiBaseUrl } : {}),
    });
  }

  /**
   * 解析 modelId → vendor 实例 + 规范化具体 modelId(落账 modelName / 计费 priceTable 用规范化后的)。
   * 命名约定:
   *   "deepseek-v4-pro" / "deepseek-v4-flash" / "deepseek"(裸键)→ deepseek
   *   "gemini-2.5-flash" / "gemini"(裸键)                      → gemini
   *   "qwen-max"(将来)                                         → qwen
   * 裸键(无 "-" 版本)→ 解析到 config 配的默认型号;带版本 → 原样直传 SDK。
   */
  resolve(modelId: string): { model: LanguageModel; provider: string; modelId: string } {
    if (modelId === 'deepseek' || modelId.startsWith('deepseek-')) {
      const canonical = modelId === 'deepseek' ? this.defaultModel : modelId;
      return { model: this.deepseek(canonical), provider: 'deepseek', modelId: canonical };
    }
    if (modelId === 'gemini' || modelId.startsWith('gemini-')) {
      const canonical = modelId === 'gemini' ? this.geminiDefaultModel : modelId;
      return { model: this.google(canonical), provider: 'gemini', modelId: canonical };
    }
    throw new Error(`Unsupported model id: ${modelId}(支持 deepseek-* / gemini-* 前缀或裸键,后续扩 qwen-*)`);
  }

  getDefaultModelId(): string {
    return this.defaultModel;
  }
}
