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

const TARGETS = [
  { file: 'commercial_v02/main_image.html', selector: '#main-image', name: '渚咖咖啡杯_主图_800x800', width: 800, height: 800 },
  { file: 'commercial_v02/home_banner.html', selector: '#home-banner', name: '渚咖咖啡杯_首页banner_1200x2000', width: 1200, height: 2000 },
];

(async () => {
  const root = path.resolve(__dirname, '..');
  const outDir = path.join(root, 'deliverables', 'commercial_v02');
  fs.mkdirSync(outDir, { recursive: true });
  const browser = await chromium.launch({ channel: 'chrome', headless: true });
  const page = await browser.newPage({ viewport: { width: 1400, height: 1200 }, 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.check('20px XiqueZhaopai') && document.fonts.check('20px XiqueJuzhen'));

    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,
      pngBytes: fs.statSync(pngPath).size,
      jpgBytes: fs.statSync(jpgPath).size,
    };
    if (!checks.sizeOk || !checks.noBrokenImages || !checks.fontsLoaded || 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 }, null, 2));
  if (failed) process.exit(1);
})();
