import { detectProvider, generateGptJson, GPT_TEXT_MODEL } from './providers';
import { renderCharacterSummary, TEXT_TEMPLATES } from './templates';
import type { GenSession, TextAsset, TextTemplate } from './types';

type TextGenerationJson = {
  items?: Array<{
    templateId?: string;
    content?: string;
  }>;
};

function fallbackContent(template: TextTemplate, character: string) {
  return [
    `# ${template.title}`,
    '',
    template.description,
    '',
    '## 角色基准',
    character,
    '',
    '## 待完善',
    '未配置文本模型时生成占位稿；请在 GPT 文本模型可用后重新生成。',
  ].join('\n');
}

function normalizeContent(value: unknown) {
  return typeof value === 'string' && value.trim() ? value.trim() : '';
}

export async function generateTextAssets(opts: {
  session: GenSession;
  templateIds?: string[];
}): Promise<{ textAssets: TextAsset[]; provider: 'mock' | 'gpt' }> {
  if (!opts.session.characterSpec) throw new Error('characterSpec required');
  const allowed = new Set(opts.templateIds?.filter(Boolean) ?? TEXT_TEMPLATES.map(template => template.id));
  const templates = TEXT_TEMPLATES.filter(template => allowed.has(template.id));
  if (!templates.length) throw new Error('no text templates selected');

  const character = renderCharacterSummary(opts.session.characterSpec);
  const packSummary = (opts.session.packs ?? [])
    .map(pack => `${pack.kind}: ${pack.assets.length} images`)
    .join('; ');
  const templateInstructions = templates.map(template => ({
    templateId: template.id,
    title: template.title,
    kind: template.kind,
    outputFormat: template.outputFormat,
    prompt: template.promptTemplate.replace('{character}', character),
  }));
  const fallback: TextGenerationJson = {
    items: templates.map(template => ({
      templateId: template.id,
      content: fallbackContent(template, character),
    })),
  };

  const json = await generateGptJson<TextGenerationJson>({
    fallback,
    prompt: [
      '你是玩具专利、工厂打样和宣发文案工作流助手。',
      '请只输出 JSON，不要输出 Markdown 代码块。',
      'JSON 结构必须为 {"items":[{"templateId":"...","content":"..."}]}。',
      'content 可以是中文 Markdown 文本；表格类内容使用 Markdown 表格。',
      '要求：围绕锁定角色设定，不改变角色外观；避免编造真实商标、认证编号、价格和法律结论；待确认项要明确标注。',
      '',
      `角色设定：\n${character}`,
      `图片包进度：${packSummary || '暂无'}`,
      '',
      `请生成以下 ${templates.length} 个文案模板：`,
      JSON.stringify(templateInstructions, null, 2),
    ].join('\n'),
  });

  const byTemplate = new Map((json.items ?? []).map(item => [item.templateId, normalizeContent(item.content)]));
  const now = Date.now();
  const provider = detectProvider();
  return {
    provider,
    textAssets: templates.map(template => ({
      id: `txt_${opts.session.id}_${template.id}`,
      templateId: template.id,
      kind: template.kind,
      title: template.title,
      description: template.description,
      outputFormat: template.outputFormat,
      content: byTemplate.get(template.id) || fallbackContent(template, character),
      prompt: template.promptTemplate.replace('{character}', character),
      status: 'complete',
      provider,
      model: provider === 'gpt' ? GPT_TEXT_MODEL : 'mock',
      createdAt: now,
    })),
  };
}
