import { NextResponse } from "next/server";

const OLLAMA_URL = process.env.OLLAMA_BASE_URL?.replace(/\/v1$/, "") || "http://localhost:11434";

export async function GET() {
  let models: string[] = [];
  let detectedModel = process.env.OLLAMA_MODEL || null;

  try {
    const res = await fetch(`${OLLAMA_URL}/api/tags`, { signal: AbortSignal.timeout(3000) });
    if (res.ok) {
      const data = await res.json();
      models = (data.models || []).map((m: any) => m.name);
      if (!detectedModel && models.length > 0) {
        // Auto-pick: prefer smaller models first
        const preferred = ["gemma4", "gemma3", "gemma", "llama3.2", "llama3", "phi", "qwen", "mistral"];
        for (const p of preferred) {
          const match = models.find((m: string) => m.toLowerCase().includes(p));
          if (match) { detectedModel = match; break; }
        }
        if (!detectedModel) detectedModel = models[0];
      }
    }
  } catch { /* offline */ }

  return NextResponse.json({
    model: detectedModel || "?",
    models,
    autoDetected: !process.env.OLLAMA_MODEL,
    ollamaUrl: OLLAMA_URL,
  });
}
