'use strict';
// step-2 基线生图：用移植的素颜霜prompt，每张带产品图，生成3张到 output/
// 探地基基线 —— 不是达标测试，是看gpt-image-2出素颜霜种草图的底子
require('dotenv').config();
const path = require('path');
const fs = require('fs');
const { imageEdit, saveResult } = require('./aiClient');
const { PRODUCT, ROLES, buildImagePrompt } = require('./suyanshuang_data');

const MODEL = process.env.MODEL_IMAGE || 'gpt-image-2';
const SIZE = process.env.IMAGE_SIZE || '1024x1536';
const PRODUCT_IMG = '/Users/qiyu/Documents/企业培训项目/万牛会L1准备/产品包系统测试资料/产品白底图/素颜霜/IMG_9439.JPG';
const OUT_DIR = path.join(__dirname, 'output');

const JOBS = [
  { role: 'hook', file: '02_封面hook.png' },
  { role: 'texture', file: '03_质感texture.png' },
  { role: 'closer', file: '04_软转化closer.png' },
];

async function runOne(job) {
  const r = ROLES[job.role];
  const prompt = buildImagePrompt(job.role);
  const traceId = `clover-baseline-${job.role}`;
  console.log(`\n── [${r.name}] 开始生成 ──`);
  console.log(`  模型=${MODEL} 尺寸=${SIZE} 产品图=${path.basename(PRODUCT_IMG)}`);
  const t0 = Date.now();
  try {
    const result = await imageEdit({
      images: [PRODUCT_IMG],
      prompt,
      traceId,
      model: MODEL,
      size: SIZE,
    });
    const outPath = path.join(OUT_DIR, job.file);
    await saveResult(result, outPath);
    const ms = Date.now() - t0;
    const kb = fs.existsSync(outPath) ? Math.round(fs.statSync(outPath).size / 1024) : 0;
    console.log(`  ✅ 完成 用时${ms}ms 大小${kb}KB → ${job.file}`);
    return { role: job.role, ok: true, ms, kb, file: job.file };
  } catch (e) {
    const ms = Date.now() - t0;
    console.log(`  ❌ 失败 用时${ms}ms：${e.message}`);
    return { role: job.role, ok: false, ms, err: e.message };
  }
}

(async () => {
  if (!fs.existsSync(OUT_DIR)) fs.mkdirSync(OUT_DIR, { recursive: true });
  if (!fs.existsSync(PRODUCT_IMG)) {
    console.error(`产品图不存在：${PRODUCT_IMG}`);
    process.exit(1);
  }
  console.log(`===== Clover 基线生图测试 =====`);
  console.log(`产品：${PRODUCT.name}｜成分：${PRODUCT.ingredients.join('/')}`);
  const results = [];
  for (const job of JOBS) {
    // 串行跑，避免并发触发中转站限流；一张一张看结果
    results.push(await runOne(job));
  }
  console.log(`\n===== 汇总 =====`);
  for (const r of results) {
    if (r.ok) console.log(`  ${r.role}: ✅ ${r.ms}ms ${r.kb}KB`);
    else console.log(`  ${r.role}: ❌ ${r.err}`);
  }
  const okN = results.filter((r) => r.ok).length;
  console.log(`\n成功 ${okN}/${JOBS.length} 张，输出目录：${OUT_DIR}`);
})();
