// retoor <retoor@molodetz.nl>
export default class AiClient {
  constructor(config) {
    this.endpoint = config.endpoint;
    this.model = config.model;
    this.apiKey = config.apiKey;
    this.temperature = config.temperature;
  }

  async complete(messages, tools) {
    const body = {
      model: this.model,
      messages,
      temperature: this.temperature,
    };
    if (tools && tools.length) {
      body.tools = tools;
      body.tool_choice = "auto";
    }

    const response = await fetch(this.endpoint, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + this.apiKey,
      },
      body: JSON.stringify(body),
    });

    if (!response.ok) {
      const detail = await response.text().catch(() => "");
      throw new Error("md-clippy AI request failed (" + response.status + "): " + detail);
    }

    const data = await response.json();
    if (data.error) {
      const message = data.error.message || JSON.stringify(data.error);
      throw new Error("md-clippy AI error: " + message);
    }

    const choice = data.choices && data.choices[0];
    if (!choice || !choice.message) {
      throw new Error("md-clippy AI returned no message");
    }
    return choice.message;
  }
}
