import Anthropic from '@anthropic-ai/sdk';

let client;

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

export async function generate(images, systemPrompt) {
  const content = [];
  for (const img of images) {
    content.push({
      type: 'image',
      source: { type: 'base64', media_type: img.mediaType, data: img.base64 },
    });
  }
  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().messages.create({
    model: 'claude-sonnet-4-20250514',
    max_tokens: 1500,
    system: systemPrompt,
    messages: [{ role: 'user', content }],
  });

  const text = response.content[0].text;
  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().messages.create({
    model: 'claude-sonnet-4-20250514',
    max_tokens: 1400,
    system: systemPrompt,
    messages: [{ role: 'user', content: String(userPrompt || '') }],
  });
  return response.content?.map(part => part.type === 'text' ? part.text : '').join('\n').trim();
}
