import { NextRequest } from 'next/server';
import { OLLAMA_URL } from '../../../lib/ollama-config';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { model, prompt, images } = body;

    const response = await fetch(`${OLLAMA_URL}/api/generate`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ model, prompt, stream: true, ...(images ? { images } : {}) }),
    });

    if (!response.ok || !response.body) {
      return new Response(JSON.stringify({ error: `Ollama error: ${response.status}` }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' },
      });
    }

    // Pipe the Ollama stream directly to the client
    return new Response(response.body, {
      headers: {
        'Content-Type': 'application/x-ndjson',
        'Transfer-Encoding': 'chunked',
        'Cache-Control': 'no-cache',
      },
    });
  } catch (err) {
    return new Response(JSON.stringify({ error: String(err) }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' },
    });
  }
}
