import { Logger } from "@nestjs/common";

const logger = new Logger("OllamaClient");

const OLLAMA_BASE_URL = process.env.OLLAMA_URL ?? "http://172.22.0.1:11434";
const OLLAMA_MODEL = process.env.OLLAMA_MODEL ?? "llama3.2:3b";
const TIMEOUT_MS = 90_000;

export async function generateOllamaText(prompt: string): Promise<string | null> {
  try {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);

    const res = await fetch(`${OLLAMA_BASE_URL}/api/generate`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      signal: controller.signal,
      body: JSON.stringify({
        model: OLLAMA_MODEL,
        prompt,
        stream: false,
        options: {
          temperature: 0.6,
          num_predict: 150,
          repeat_penalty: 1.1,
        },
      }),
    });

    clearTimeout(timer);

    if (!res.ok) {
      logger.warn(`Ollama HTTP ${res.status}`);
      return null;
    }

    const data = await res.json() as { response?: string };
    return data.response?.trim() ?? null;
  } catch (err: unknown) {
    if ((err as Error).name === "AbortError") {
      logger.warn("Ollama request timed out");
    } else {
      logger.warn(`Ollama error: ${(err as Error).message}`);
    }
    return null;
  }
}
