import OpenAI from 'openai';

let client;

function getClient() {
  if (!client) client = new OpenAI();
  return client;
}

export async function generate(images, systemPrompt) {
  const content = [];
  for (const img of images) {
    content.push({
      type: 'image_url',
      image_url: { url: `data:${img.mediaType};base64,${img.base64}`, detail: 'high' },
    });
  }
  content.push({ type: 'text', text: 'Analysiere die Fotos und erstelle das Listing gemäß den Anweisungen. Antworte ausschließlich mit validem JSON.' });

  const response = await getClient().chat.completions.create({
    model: 'gpt-4o',
    max_tokens: 1500,
    messages: [
      { role: 'system', content: systemPrompt },
      { role: 'user', content },
    ],
  });

  const text = response.choices[0].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) {
  const response = await getClient().chat.completions.create({
    model: 'gpt-4o',
    max_tokens: 1400,
    messages: [
      { role: 'system', content: String(systemPrompt || '') },
      { role: 'user', content: String(userPrompt || '') },
    ],
  });
  return String(response.choices?.[0]?.message?.content || '').trim();
}
