const puppeteer = require('puppeteer-core');
const http = require('http');
const fs = require('fs');
const path = require('path');

function startServer(root, port) {
  return new Promise(resolve => {
    const srv = http.createServer((req, res) => {
      let fp = path.join(root, decodeURIComponent(req.url.split('?')[0]));
      if (!fs.existsSync(fp) || fs.statSync(fp).isDirectory()) fp = path.join(root, 'index-v2.html');
      const ext = path.extname(fp).toLowerCase();
      const mime = { '.html':'text/html', '.js':'application/javascript', '.css':'text/css', '.png':'image/png', '.jpg':'image/jpeg' };
      try { res.writeHead(200, { 'Content-Type': mime[ext] || 'application/octet-stream' }); fs.createReadStream(fp).pipe(res); }
      catch(e) { res.writeHead(404); res.end(); }
    });
    srv.listen(port, () => resolve(srv));
  });
}

(async () => {
  const root = 'C:\\Users\\Administrator\\lab-safety-monitor';
  const port = 19527;
  const srv = await startServer(root, port);

  const browser = await puppeteer.launch({
    executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
    headless: 'new',
    args: ['--no-sandbox','--disable-setuid-sandbox','--window-size=9600,2800']
  });

  const page = await browser.newPage();
  await page.setViewport({ width: 9600, height: 2800, deviceScaleFactor: 1 });
  await page.goto(`http://localhost:${port}/index-v2.html`, { waitUntil: 'networkidle0', timeout: 30000 });

  await new Promise(r => setTimeout(r, 2000));
  // 关闭预警弹窗
  await page.evaluate(() => {
    const modal = document.getElementById('alert-modal');
    if (modal) modal.style.display = 'none';
    window.showAlert = () => {};
  });
  // 等待摄像头初始化
  await new Promise(r => setTimeout(r, 5000));

  await page.screenshot({ path: 'C:\\Users\\Administrator\\lab-safety-monitor\\design-preview.png', fullPage: true });
  console.log('Done');
  await browser.close();
  srv.close();
})().catch(e => { console.error(e.message); process.exit(1); });
