import { Injectable } from '@nestjs/common';
import { ChatOpenAI } from '@langchain/openai';
import { ModelConfig } from '../types';

@Injectable()
export class ApiService {
  constructor() { }

  
  healthCheck() {
    return { status: 'ok', message: 'API is healthy' };
  }

  async getChatCompletion(
    prompt: string,
    modelConfig: ModelConfig,
  ): Promise<string> {
    // API key is optional - allow local models

    try {
      const llm = this.createLLM(modelConfig);
      const response = await llm.invoke(prompt);
      return response.content.toString();
    } catch (error) {
      console.error('LangChain call failed:', error);
      if (error.message?.includes('401')) {
        throw new Error('Invalid API key');
      }
      throw new Error('Failed to get response: ' + error.message);
    }
  }

  private createLLM(modelConfig: ModelConfig): ChatOpenAI {
    return new ChatOpenAI({
      temperature: 0.7,
      apiKey: modelConfig.apiKey,
      modelName: modelConfig.modelId,
      configuration: {
        baseURL: modelConfig.baseUrl || 'http://localhost:11434/v1',
      },
    });
  }
}
