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

/**
 * AiProviderService — 模型工厂。
 *
 * harness 原则:AiCall 只声明 modelId 字符串,provider 决定怎么实例化。
 * 这里集中处理 vendor 路由(目前只有 deepseek;以后加 qwen 时本类内部扩 switch)。
 *
 * 设计选择:
 *   - DeepSeek 走官方 SDK @ai-sdk/deepseek(国内 endpoint,合规)
 *   - 不走 Vercel AI Gateway(美国基建,数据出境)
 *   - modelId 字符串直传,不硬编码 enum(SDK v2.0.35 支持任意 string)
 */
@Injectable()
export class AiProviderService {
  private readonly logger = new Logger(AiProviderService.name);
  private readonly deepseek: DeepSeekProvider;
  private readonly defaultModel: string;

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

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

  /**
   * 解析 modelId → vendor + 实例。
   * 命名约定:
   *   "deepseek-v4-pro"          → deepseek
   *   "deepseek-v4-flash"        → deepseek
   *   "qwen-max"(将来)         → qwen
   */
  resolve(modelId: string): { model: LanguageModel; provider: string } {
    if (modelId.startsWith('deepseek-')) {
      return { model: this.deepseek(modelId), provider: 'deepseek' };
    }
    throw new Error(`Unsupported model id: ${modelId}(只支持 deepseek-* 前缀,后续扩 qwen-*)`);
  }

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