const { chromium } = require('playwright');
const fs = require('fs');
const path = require('path');
(async () => {
  const root = path.resolve(__dirname, '..');
  const htmlPath = path.join(__dirname, 'detail.html');
  const outDir = path.join(root, 'deliverables');
  const sectionDir = path.join(outDir, 'sections_v03');
  fs.mkdirSync(sectionDir, { recursive: true });
  const browser = await chromium.launch({ channel: 'chrome', headless: true });
  const page = await browser.newPage({ viewport: { width: 790, height: 1600 }, deviceScaleFactor: 1 });
  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 full = path.join(outDir, '渚咖咖啡杯_详情页_v03_full.png');
  await page.locator('.page').screenshot({ path: full });
  const sections = await page.locator('[data-section]').evaluateAll(nodes => nodes.map(n => n.getAttribute('data-section')));
  for (const name of sections) {
    const safe = name.replace(/[\\/:*?"<>|]/g, '_');
    await page.locator(`[data-section="${name}"]`).screenshot({ path: path.join(sectionDir, `${safe}.png`) });
  }
  const size = await page.locator('.page').evaluate(el => ({ width: el.offsetWidth, height: el.scrollHeight }));
  const broken = await page.evaluate(() => Array.from(document.images).filter(i => !i.naturalWidth).map(i => i.getAttribute('src')));
  fs.writeFileSync(path.join(outDir, 'export_manifest_v03.json'), JSON.stringify({ full, sections, size, broken, exportedAt: new Date().toISOString() }, null, 2));
  await browser.close();
  console.log(JSON.stringify({ ok: true, full, sectionCount: sections.length, size, broken }, null, 2));
})();
