interface DeepSeekConfig {
  apiKey: string;
  baseURL: string;
  model: string;
}

interface ModelOption {
  id: string;
  name: string;
  description: string;
  config: DeepSeekConfig;
}

interface DeepSeekMessage {
  role: 'system' | 'user' | 'assistant';
  content: string;
}

interface DeepSeekRequest {
  model: string;
  messages: DeepSeekMessage[];
  temperature?: number;
  max_tokens?: number;
  stream?: boolean;
}

interface DeepSeekResponse {
  id: string;
  object: string;
  created: number;
  model: string;
  choices: Array<{
    index: number;
    message: {
      role: string;
      content: string;
    };
    finish_reason: string;
  }>;
  usage: {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
  };
}

class DeepSeekService {
  private config: DeepSeekConfig;
  private readonly modelOptions: ModelOption[] = [
    {
      id: 'deepseek',
      name: 'DeepSeek Chat',
      description: 'DeepSeek 深度思考模型，适合复杂问题分析',
      config: {
        apiKey: 'sk-71f583d8c182420d9d2001f01aa2b643', // 预配置的DeepSeek API Key
        baseURL: 'https://api.deepseek.com',
        model: 'deepseek-chat'
      }
    },
    {
      id: 'openai-gpt4o-mini',
      name: 'GPT-4o Mini',
      description: 'OpenAI GPT-4o Mini 模型，快速响应',
      config: {
        apiKey: 'sk-m5oOhoMo9l3QboachCkbIjRAetfc0c1DCcBPvHUs8U3cMzS2', // 预配置的OpenAI API Key
        baseURL: 'https://aicvw.com',
        model: 'gpt-4o-mini'
      }
    }
  ];

  constructor() {
    // 默认使用第一个模型
    this.config = { ...this.modelOptions[0].config };
  }

  // 获取可用模型列表
  getModelOptions(): ModelOption[] {
    return this.modelOptions;
  }

  // 根据模型ID切换模型
  switchModel(modelId: string) {
    const selectedModel = this.modelOptions.find(model => model.id === modelId);
    if (selectedModel) {
      this.config = { ...selectedModel.config };
      return true;
    }
    return false;
  }

  // 获取当前模型信息
  getCurrentModel(): ModelOption | undefined {
    return this.modelOptions.find(
      model => model.config.model === this.config.model && model.config.baseURL === this.config.baseURL
    );
  }

  // 设置 API Key (保留兼容性)
  setApiKey(apiKey: string) {
    this.config.apiKey = apiKey;
  }

  // 设置模型 (保留兼容性)
  setModel(model: string) {
    this.config.model = model;
  }

  // 检查配置是否完整
  private validateConfig(): boolean {
    if (!this.config.apiKey) {
      console.error('API Key 未设置');
      return false;
    }
    return true;
  }

  // 发送聊天请求
  async chat(
    messages: DeepSeekMessage[],
    options?: {
      temperature?: number;
      maxTokens?: number;
      stream?: boolean;
    }
  ): Promise<DeepSeekResponse> {
    if (!this.validateConfig()) {
      throw new Error('API 配置不完整');
    }

    const requestBody: DeepSeekRequest = {
      model: this.config.model,
      messages,
      temperature: options?.temperature || 0.7,
      max_tokens: options?.maxTokens || 2000,
      stream: options?.stream || false
    };

    try {
      const response = await fetch(`${this.config.baseURL}/v1/chat/completions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${this.config.apiKey}`
        },
        body: JSON.stringify(requestBody)
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(`API 请求失败: ${response.status} ${response.statusText} - ${errorData.error?.message || ''}`);
      }

      const data = await response.json();
      return data;
    } catch (error) {
      console.error('API 调用错误:', error);
      throw error;
    }
  }

  // 流式聊天请求
  async streamChat(
    messages: DeepSeekMessage[],
    onChunk: (chunk: string) => void,
    onComplete: () => void,
    onError: (error: Error) => void,
    options?: {
      temperature?: number;
      maxTokens?: number;
    }
  ): Promise<void> {
    if (!this.validateConfig()) {
      onError(new Error('API 配置不完整'));
      return;
    }

    const requestBody: DeepSeekRequest = {
      model: this.config.model,
      messages,
      temperature: options?.temperature || 0.7,
      max_tokens: options?.maxTokens || 2000,
      stream: true
    };

    try {
      const response = await fetch(`${this.config.baseURL}/v1/chat/completions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${this.config.apiKey}`
        },
        body: JSON.stringify(requestBody)
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(`API 请求失败: ${response.status} ${response.statusText} - ${errorData.error?.message || ''}`);
      }

      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error('无法读取响应流');
      }

      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();

        if (done) {
          onComplete();
          break;
        }

        const chunk = decoder.decode(value);
        const lines = chunk.split('\n');

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6);

            if (data === '[DONE]') {
              onComplete();
              return;
            }

            try {
              const parsed = JSON.parse(data);
              const content = parsed.choices?.[0]?.delta?.content;
              if (content) {
                onChunk(content);
              }
            } catch (parseError) {
              // 忽略解析错误，继续处理下一行
            }
          }
        }
      }
    } catch (error) {
      console.error('流式请求错误:', error);
      onError(error as Error);
    }
  }

  // 生成最终回答
  async generateAnswer(question: string, thinkingProcess: string): Promise<string> {
    const answerPrompt: DeepSeekMessage[] = [
      {
        role: 'system',
        content:
          '你是一个专业的AI助手，善于给出详细、准确的回答。请基于之前的思考过程，给出最终的完整答案。如果涉及代码，请提供完整的、可运行的代码示例。使用Markdown格式回复。'
      },
      {
        role: 'user',
        content: `问题：${question}\n\n我的思考过程：\n${thinkingProcess}\n\n请基于以上思考，给出详细的最终答案。`
      }
    ];

    try {
      const response = await this.chat(answerPrompt, { temperature: 0.7, maxTokens: 2000 });
      return response.choices[0]?.message?.content || '抱歉，我无法生成回答。';
    } catch (error) {
      console.error('生成最终答案失败:', error);
      throw error;
    }
  }
}

// 导出单例实例
export const deepSeekService = new DeepSeekService();

// 导出类型
export type { DeepSeekMessage, DeepSeekResponse, ModelOption };
