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 { createOpenAICompatible, type OpenAICompatibleProvider } from '@ai-sdk/openai-compatible';
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 qwen: OpenAICompatibleProvider;
  private readonly defaultModel: string;
  private readonly geminiDefaultModel: string;
  private readonly qwenDefaultModel: string;

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

    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 } : {}),
    });

    if (!ai.qwenApiKey) {
      this.logger.warn('QWEN_API_KEY(或 DASHSCOPE_API_KEY)未设置 — Qwen 调用会失败。到阿里云百炼 dashscope 申请');
    }
    // 通义千问走 DashScope OpenAI-兼容端点(compatible-mode)。
    // DashScope 支持 OpenAI json_schema 严格模式(实测严格按 schema 返),但两个前提:
    //   ① supportsStructuredOutputs: true → SDK 才发 response_format=json_schema(否则松散 json_object 不符 schema)
    //   ② prompt 里必须出现 "json" 字样(DashScope 硬性校验)— 由 runner 对 qwen 注入(见 buildQwenSystem)
    this.qwen = createOpenAICompatible({
      name: 'qwen',
      apiKey: ai.qwenApiKey,
      baseURL: ai.qwenBaseUrl,
      supportsStructuredOutputs: true,
      // qwen3.7-max 是推理模型:流式下 thinking 会污染 content 流 → 结构化 JSON 解析失败。
      // DashScope 用 body 里 enable_thinking:false 关思考(SDK 无此参数,用 fetch 中间件注入)。
      fetch: (async (url: string | URL | Request, options?: RequestInit) => {
        if (options?.body && typeof options.body === 'string') {
          try {
            const b = JSON.parse(options.body) as Record<string, unknown>;
            b.enable_thinking = false;
            options = { ...options, body: JSON.stringify(b) };
          } catch {
            /* 非 JSON body 不动 */
          }
        }
        return fetch(url, options);
      }) as typeof fetch,
    });
  }

  /**
   * 解析 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 };
    }
    // qwen 前缀(含 qwen3.7-max / qwen-max / 裸键 qwen)→ DashScope 兼容端点
    if (modelId.startsWith('qwen')) {
      const canonical = modelId === 'qwen' ? this.qwenDefaultModel : modelId;
      return { model: this.qwen(canonical), provider: 'qwen', modelId: canonical };
    }
    throw new Error(`Unsupported model id: ${modelId}(支持 deepseek-* / gemini-* / qwen* 前缀或裸键)`);
  }

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