const { chromium } = require('playwright');
const fs = require('fs');
const path = require('path');

const TARGETS = [
  { file: 'commercial_v07/main_01.html', selector: '#main-image', name: '渚咖咖啡杯_主图01_良渚文创_800x800', width: 800, height: 800 },
  { file: 'commercial_v07/main_02.html', selector: '#main-image', name: '渚咖咖啡杯_主图02_两款可选_800x800', width: 800, height: 800 },
  { file: 'commercial_v07/main_03.html', selector: '#main-image', name: '渚咖咖啡杯_主图03_顺手杯柄_800x800', width: 800, height: 800 },
  { file: 'commercial_v07/main_04.html', selector: '#main-image', name: '渚咖咖啡杯_主图04_良渚刻符_800x800', width: 800, height: 800 },
  { file: 'commercial_v07/main_05.html', selector: '#main-image', name: '渚咖咖啡杯_主图05_雅致礼赠_800x800', width: 800, height: 800 },
];

(async () => {
  const root = path.resolve(__dirname, '..');
  const outDir = path.join(root, 'deliverables', 'commercial_v07');
  fs.mkdirSync(outDir, { recursive: true });
  const browser = await chromium.launch({ channel: 'chrome', headless: true });
  const page = await browser.newPage({ viewport: { width: 1000, height: 1000 }, deviceScaleFactor: 1 });
  const results = [];
  let failed = false;

  for (const t of TARGETS) {
    const htmlPath = path.join(__dirname, t.file);
    await page.goto('file://' + htmlPath, { waitUntil: 'load' });
    await page.waitForLoadState('networkidle');
    await page.evaluate(async () => {
      if (document.fonts && document.fonts.ready) await document.fonts.ready;
      await Promise.all(Array.from(document.images).map(img => img.complete ? true : new Promise(resolve => { img.onload = img.onerror = resolve; })));
    });

    const box = await page.locator(t.selector).evaluate(el => ({ width: el.offsetWidth, height: el.offsetHeight }));
    const broken = await page.evaluate(() => Array.from(document.images).filter(i => !i.naturalWidth).map(i => i.getAttribute('src')));
    const fontsOk = await page.evaluate(() => document.fonts && document.fonts.status === 'loaded');
    const visibleText = await page.locator(t.selector).innerText();
    const noLogoPad = await page.evaluate(() => !document.querySelector('.logo-pad'));

    const pngPath = path.join(outDir, `${t.name}.png`);
    const jpgPath = path.join(outDir, `${t.name}.jpg`);
    await page.locator(t.selector).screenshot({ path: pngPath });
    await page.locator(t.selector).screenshot({ path: jpgPath, type: 'jpeg', quality: 92 });

    const checks = {
      sizeOk: box.width === t.width && box.height === t.height,
      noBrokenImages: broken.length === 0,
      fontsLoaded: fontsOk,
      noLogoPad,
      visibleText,
      visibleTextLength: Array.from(visibleText.trim()).length,
      pngBytes: fs.statSync(pngPath).size,
      jpgBytes: fs.statSync(jpgPath).size,
    };
    if (!checks.sizeOk || !checks.noBrokenImages || !checks.fontsLoaded || !checks.noLogoPad || checks.visibleTextLength > 4 || checks.pngBytes < 30000) failed = true;
    results.push({ ...t, box, broken, checks, png: pngPath, jpg: jpgPath });
  }

  await browser.close();
  fs.writeFileSync(path.join(outDir, 'export_manifest.json'), JSON.stringify({ results, exportedAt: new Date().toISOString() }, null, 2));
  console.log(JSON.stringify({ ok: !failed, results: results.map(r => ({ name: r.name, box: r.box, checks: r.checks })) }, null, 2));
  if (failed) process.exit(1);
})();
