import { SystemConfig } from '../types';

export class OllamaService {
  private config: SystemConfig;

  constructor(config: SystemConfig) {
    this.config = config;
  }

  updateConfig(config: SystemConfig) {
    this.config = config;
  }



  async testConnection(): Promise<boolean> {
    try {
      const response = await fetch(`${this.config.ollamaUrl}/api/tags`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      return response.ok;
    } catch (error) {
      console.error('Ollama连接测试失败:', error);
      return false;
    }
  }

  async getAvailableModels(): Promise<string[]> {
    try {
      const response = await fetch(`${this.config.ollamaUrl}/api/tags`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      return data.models?.map((model: any) => model.name) || [];
    } catch (error) {
      console.error('获取模型列表失败:', error);
      return [];
    }
  }

  async getAvailableModelsWithInfo(): Promise<any[]> {
    try {
      const response = await fetch(`${this.config.ollamaUrl}/api/tags`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      return data.models || [];
    } catch (error) {
      console.error('获取模型详细信息失败:', error);
      return [];
    }
  }

  async chat(userMessage: string, context: string): Promise<string> {
    const systemPrompt = `你是一位专业的写作助手和创意顾问，擅长帮助作者进行小说创作。你可以：
1. 讨论情节构思和发展
2. 分析人物性格和关系
3. 提供场景设置建议
4. 解决创作瓶颈
5. 提供写作技巧和指导

请根据用户的问题提供专业、有建设性的建议。`;

    const prompt = `${context}

用户问题：${userMessage}

请提供专业建议：`;

    try {
      const response = await fetch(`${this.config.ollamaUrl}/api/generate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          model: this.config.model,
          prompt: prompt,
          system: systemPrompt,
          stream: false,
          options: {
            temperature: this.config.temperature,
            top_p: this.config.topP,
            num_predict: this.config.maxTokens
          }
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      return data.response || '回复失败，请重试。';
    } catch (error) {
      console.error('Ollama聊天错误:', error);
      throw new Error('AI回复失败，请检查Ollama服务是否正常运行。');
    }
  }
}