/**
 * e2e-test.mjs — 端到端浏览器测试：上传华为动态照片 → 预览 → 导出 HEIC+MOV
 * 使用系统 Edge（下载的 Chrome 在此环境崩溃），通过 playwright-core 驱动。
 */
import pw from 'file:///C:/Users/Administrator/.workbuddy/binaries/node/workspace/node_modules/playwright-core/index.js';
const { chromium } = pw;
import fs from 'node:fs';
import path from 'node:path';

const EDGE = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe';
const PAGE_URL = 'http://127.0.0.1:8765';
const TEST_FILE = 'C:\\Users\\Administrator\\WorkBuddy\\2026-09-03-22-27-47\\testdata\\hw_livephoto.jpg';
/** 导出格式：heic | jpg（命令行参数，默认 heic） */
const FMT = (process.argv[2] === 'jpg' || process.argv[2] === 'jpeg') ? 'jpg' : 'heic';
const TAG = FMT === 'jpg' ? 'jpeg' : 'heic';
// 两种格式分目录存放，避免 MOV 同名互相覆盖后失去可配对的完整文件对
const ROOT_OUT = 'C:\\Users\\Administrator\\WorkBuddy\\2026-09-03-22-27-47\\livephoto-splitter\\test-output';
const OUT_DIR = path.join(ROOT_OUT, TAG + '-mode');
const SHOT = path.join(OUT_DIR, 'page-after-upload.png');

fs.mkdirSync(OUT_DIR, { recursive: true });
console.log(`=== 端到端测试：静态图导出格式 = ${FMT.toUpperCase()} ===`);

const consoleErrors = [];
const browser = await chromium.launch({
  executablePath: EDGE,
  headless: true,
  args: ['--no-sandbox', '--disable-gpu'],
});
const context = await browser.newContext({ acceptDownloads: true, viewport: { width: 1280, height: 900 } });
const page = await context.newPage();
page.on('console', m => { if (m.type() === 'error') consoleErrors.push(m.text()); });
page.on('pageerror', e => consoleErrors.push('PAGEERROR: ' + e.message));
page.on('response', r => { if (r.status() >= 400) consoleErrors.push(`HTTP ${r.status()}: ${r.url()}`); });

// 1. 打开页面
await page.goto(PAGE_URL, { waitUntil: 'load' });
const title = await page.title();
console.log('[1] 页面标题:', title);

// 2. 上传测试文件
await page.setInputFiles('#fileInput', TEST_FILE);
console.log('[2] 已上传 hw_livephoto.jpg');

// 3. 等待解析完成（state 变为 ok 或 err）
await page.waitForSelector('.card .state:not(.busy)', { timeout: 15000 }).catch(() => {});
await page.waitForTimeout(1500);
const stateText = await page.textContent('.card .state').catch(() => '(无)');
console.log('[3] 解析状态:', stateText.trim());

// 4. 读取元信息
const metaText = await page.textContent('.card .meta').catch(() => '(无)');
console.log('[4] 元信息:');
metaText.split('\n').map(s => s.trim()).filter(Boolean).forEach(l => console.log('    ', l));

// 4.5 选择静态图导出格式
await page.check(`input[name="photoFormat"][value="${FMT}"]`);
await page.waitForTimeout(500);
const btnLabel = await page.textContent('.act-pair').catch(() => '(无)');
console.log('[4.5] 导出按钮文案:', btnLabel.trim());
const qVisible = await page.isVisible('#qualityRow').catch(() => null);
console.log('      画质设置可见（JPEG 时应为 false）:', qVisible);

// 5. 切换到视频标签，等视频元数据
await page.click('.card .tab-btn[data-tab="vid"]').catch(() => {});
await page.waitForTimeout(2000);

// 6. 截图（含预览）
await page.screenshot({ path: SHOT, fullPage: false });
console.log('[5] 截图已保存:', SHOT);

// 7. 导出 Live Photo 对（HEIC + MOV），预先注册下载监听避免错过事件
const downloads = [];
const dlDone = new Promise(resolve => {
  const timer = setTimeout(() => resolve('timeout'), 180000);
  page.on('download', async dl => {
    try {
      const fp = path.join(OUT_DIR, dl.suggestedFilename());
      await dl.saveAs(fp);
      downloads.push(fp);
      console.log('    下载:', dl.suggestedFilename(), fs.statSync(fp).size, 'bytes');
      if (downloads.length >= 2) { clearTimeout(timer); resolve('ok'); }
    } catch (e) { consoleErrors.push('保存失败: ' + e.message); }
  });
});

await page.click('.act-pair');
await dlDone;
await page.waitForTimeout(1000);

// 等待 toast 提示
await page.waitForTimeout(1500);
const toasts = await page.$$eval('.toast', els => els.map(e => e.textContent)).catch(() => []);
console.log('[6] Toast 提示:', toasts);

// 8. 最终截图
await page.screenshot({ path: path.join(OUT_DIR, 'page-after-export.png') });

// 9. 校验下载文件魔数
console.log('[7] 下载文件校验:');
for (const fp of downloads) {
  const buf = fs.readFileSync(fp);
  const head = buf.subarray(4, 12).toString('latin1');
  console.log(`    ${path.basename(fp)}: ${buf.length} bytes, ftyp brand = "${head.trim()}"`);
}

console.log('[8] 浏览器控制台错误:', consoleErrors.length ? consoleErrors : '无');
await browser.close();
console.log('DONE');
