export const MODELS = [
  { id: 'llama3.2-vision', name: 'Llama 3.2 Vision (11B)' },
  { id: 'llava', name: 'LLaVA 1.6 (7B)' },
  { id: 'moondream', name: 'Moondream 2 (1.8B, schnell)' },
  { id: 'gemma3', name: 'Gemma 3 (Vision)' },
];

export async function generate(images, systemPrompt, model) {
  const baseUrl = process.env.OLLAMA_URL || 'http://localhost:11434';
  const modelId = model || MODELS[0].id;

  const ollamaImages = images.map(img => img.base64);

  const res = await fetch(`${baseUrl}/api/chat`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      model: modelId,
      stream: false,
      messages: [
        { role: 'system', content: systemPrompt },
        {
          role: 'user',
          content: 'Analysiere die Fotos und erstelle das Listing gemäß den Anweisungen. Antworte ausschließlich mit validem JSON.',
          images: ollamaImages,
        },
      ],
    }),
  });

  if (!res.ok) {
    const text = await res.text().catch(() => '');
    throw new Error(`Ollama Fehler (${res.status}): ${text.slice(0, 200)}`);
  }

  const data = await res.json();
  const text = data.message.content;
  const jsonMatch = text.match(/\{[\s\S]*\}/);
  if (!jsonMatch) throw new Error('AI returned no valid JSON');
  return JSON.parse(jsonMatch[0]);
}

export async function generateText(systemPrompt, userPrompt, model) {
  const baseUrl = process.env.OLLAMA_URL || 'http://localhost:11434';
  const modelId = model || MODELS[0].id;
  const res = await fetch(`${baseUrl}/api/chat`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      model: modelId,
      stream: false,
      messages: [
        { role: 'system', content: String(systemPrompt || '') },
        { role: 'user', content: String(userPrompt || '') },
      ],
    }),
  });
  if (!res.ok) {
    const text = await res.text().catch(() => '');
    throw new Error(`Ollama Fehler (${res.status}): ${text.slice(0, 200)}`);
  }
  const data = await res.json();
  return String(data.message?.content || '').trim();
}
