// B35 小红书 8 张卡片渲染器 — 2160×2880 @2x, deviceScaleFactor=2
// v6a-center-fill 居中铺满 1080（小红书 3:4 画布 1080×1440）
// 10-brand 单 logo 范式（暗色底 #0D0D12 + 中央 280，不叠加 v6a-bleed）
// 末尾必跑 Compress-Archive 打 xiaohongshu.zip（B29 踩坑：不能再漏打包）
const { chromium } = require('C:\\Users\\Rus\\.npm-global\\node_modules\\playwright');
const { execSync } = require('child_process');
const path = require('path');
const fs = require('fs');

const cards = [
  { html: '01-cover.html',   png: '01-cover.png' },
  { html: '02-分栏.html',    png: '02-分栏.png' },
  { html: '03-数据.html',    png: '03-数据.png' },
  { html: '04-步骤1.html',   png: '04-步骤1.png' },
  { html: '05-步骤2.html',   png: '05-步骤2.png' },
  { html: '06-步骤3.html',   png: '06-步骤3.png' },
  { html: '07-金句.html',    png: '07-金句.png' },
  { html: '10-品牌.html',    png: '10-品牌.png' },
];

(async () => {
  const browser = await chromium.launch({
    headless: true,
    args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage'],
  });

  let totalBytes = 0;
  const cardBytes = {};
  const dir = __dirname;
  for (const c of cards) {
    const htmlPath = path.join(dir, c.html);
    const pngPath = path.join(dir, c.png);
    const context = await browser.newContext({
      viewport: { width: 1080, height: 1440 },
      deviceScaleFactor: 2,  // 强制 @2x 高清（2160×2880 物理像素）
    });
    const page = await context.newPage();
    await page.goto('file://' + htmlPath.replace(/\\/g, '/'), { waitUntil: 'networkidle' });
    await page.screenshot({ path: pngPath, type: 'png', fullPage: false, clip: { x: 0, y: 0, width: 1080, height: 1440 } });
    await context.close();
    const stats = fs.statSync(pngPath);
    totalBytes += stats.size;
    cardBytes[c.png] = stats.size;
    console.log(`✅ ${c.png}  ${stats.size} B  (${(stats.size/1024).toFixed(1)} KB)`);
  }

  await browser.close();
  console.log(`\n📦 总大小: ${(totalBytes/1024).toFixed(1)} KB (${cards.length} 张)`);
  console.log(`📐 物理尺寸: 2160×2880 (deviceScaleFactor=2 @2x)`);
  console.log(`\nJSON: ${JSON.stringify(cardBytes)}`);

  // === 打包 xiaohongshu.zip（B29 踩坑：必跑，一气呵成）===
  // 12 entries 必带：8 PNG + copy.txt + title.txt + k-match.md + gen-cards.js = 12
  // 路径用 B33 范式：单引号包 powershell（单引号不转义），反斜杠先 normalize
  const zipPath = path.join(dir, '..', 'xiaohongshu.zip');
  const pngGlob = path.join(dir, '*.png').replace(/\\/g, '\\\\');
  const copyTxt = path.join(dir, 'copy.txt').replace(/\\/g, '\\\\');
  const titleTxt = path.join(dir, 'title.txt').replace(/\\/g, '\\\\');
  const kMatch = path.join(dir, 'k-match.md').replace(/\\/g, '\\\\');
  const genCards = path.join(dir, 'gen-cards.js').replace(/\\/g, '\\\\');
  const psCmd = `powershell -NoProfile -Command "Compress-Archive -Path '${pngGlob}','${copyTxt}','${titleTxt}','${kMatch}','${genCards}' -DestinationPath '${zipPath}' -Force"`;
  console.log(`\n📦 打包: ${psCmd}`);
  try {
    execSync(psCmd, { stdio: 'inherit', shell: 'powershell.exe' });
    const zipStats = fs.statSync(zipPath);
    console.log(`\n✅ xiaohongshu.zip 已打包: ${zipPath} (${(zipStats.size/1024).toFixed(1)} KB)`);
  } catch (e) {
    console.error(`\n❌ zip 打包失败: ${e.message}`);
    throw e;
  }
})();
