// 生图 provider 抽象。优先 Poe nano-banana-pro（feedback_image-gen-model），
// 没 Key 时 mock。OpenRouter 当前模型 google/gemini-3.1-pro-preview 是文本模型，
// 不能生图，所以回退是 mock 不是 OpenRouter。

import type { GenImage } from './types';

export type Provider = 'mock' | 'poe';

export function detectProvider(): Provider {
  return process.env.POE_API_KEY ? 'poe' : 'mock';
}

// Mock：返回 SVG 占位图（data URL），不真的生图
export async function generateMock(opts: {
  sessionId: string;
  prompt: string;
  count: number;
}): Promise<GenImage[]> {
  const palette = ['#ff6b35', '#3b82f6', '#10b981', '#a855f7', '#f59e0b', '#ec4899', '#06b6d4', '#84cc16', '#ef4444'];
  return Array.from({ length: opts.count }).map((_, i) => {
    const c = palette[i % palette.length];
    const c2 = palette[(i + 3) % palette.length];
    const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
      <defs><linearGradient id="g${i}" x1="0%" y1="0%" x2="100%" y2="100%">
        <stop offset="0%" stop-color="${c}"/><stop offset="100%" stop-color="${c2}"/>
      </linearGradient></defs>
      <rect width="512" height="512" fill="url(#g${i})"/>
      <circle cx="256" cy="220" r="120" fill="white" opacity="0.85"/>
      <ellipse cx="220" cy="200" rx="10" ry="14" fill="#111"/>
      <ellipse cx="292" cy="200" rx="10" ry="14" fill="#111"/>
      <path d="M210 250 Q256 285 302 250" stroke="#111" stroke-width="6" fill="none" stroke-linecap="round"/>
      <rect x="160" y="340" width="192" height="130" rx="20" fill="white" opacity="0.85"/>
      <text x="256" y="500" text-anchor="middle" font-family="monospace" font-size="20" font-weight="bold" fill="white">MOCK #${i + 1}</text>
    </svg>`;
    const dataUrl = `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`;
    return {
      id: `img_${opts.sessionId}_${i}`,
      url: dataUrl,
      prompt: opts.prompt,
      status: 'pending' as const,
      meta: { provider: 'mock', index: i },
    };
  });
}

// Poe nano-banana-pro 生图
export async function generatePoe(opts: {
  sessionId: string;
  prompt: string;
  count: number;
  refImages?: string[];
}): Promise<GenImage[]> {
  const key = process.env.POE_API_KEY;
  if (!key) throw new Error('POE_API_KEY missing');

  const messages: Array<{ role: string; content: unknown }> = [];
  if (opts.refImages && opts.refImages.length > 0) {
    messages.push({
      role: 'user',
      content: [
        { type: 'text', text: opts.prompt },
        ...opts.refImages.map(url => ({ type: 'image_url', image_url: { url } })),
      ],
    });
  } else {
    messages.push({ role: 'user', content: opts.prompt });
  }

  const calls = Array.from({ length: opts.count }).map(async (_, i) => {
    const res = await fetch('https://api.poe.com/v1/chat/completions', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
      body: JSON.stringify({ model: 'nano-banana-pro', messages, stream: false }),
    });
    if (!res.ok) throw new Error(`Poe ${res.status}: ${await res.text()}`);
    const data: { choices?: Array<{ message?: { content?: string } }> } = await res.json();
    const content = data.choices?.[0]?.message?.content || '';
    // Poe 返回里图片通常以 markdown ![alt](url) 形式
    const m = content.match(/!\[.*?\]\((https?:\/\/[^)]+)\)/) || content.match(/(https?:\/\/[^\s)]+\.(?:png|jpe?g|webp))/i);
    const url = m ? m[1] : '';
    return {
      id: `img_${opts.sessionId}_${i}`,
      url,
      prompt: opts.prompt,
      status: 'pending' as const,
      meta: { provider: 'poe', index: i, raw: content.slice(0, 200) },
    };
  });

  return Promise.all(calls);
}
