// Screenshot/video harness for the agnt browser-overlay modes.
//
// Builds a static page that embeds the exact proxy-injected __devtool bundle
// (generated by ./genbundle), serves it over http (so the metrics WebSocket
// fails async instead of throwing on file://), then drives each mode with
// Playwright's bundled Chromium and captures a PNG + a short video per mode.
//
//   go run ./docs-site/screenshots/genbundle > docs-site/screenshots/bundle.html
//   node docs-site/screenshots/capture.mjs
//
// Output: docs-site/static/img/<mode>.png and docs-site/screenshots/videos/<mode>.webm
import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {chromium} from 'playwright';

const here = path.dirname(fileURLToPath(import.meta.url));
const imgDir = path.join(here, '..', 'static', 'img');
const vidDir = path.join(here, 'videos');
const serveDir = path.join(here, '.serve');
const VIEW = {width: 1440, height: 900};

fs.mkdirSync(serveDir, {recursive: true});
fs.mkdirSync(vidDir, {recursive: true});
fs.mkdirSync(imgDir, {recursive: true});

// Build the served page: sample markup + injected bundle.
const page = fs.readFileSync(path.join(here, 'page.html'), 'utf8');
const bundle = fs.readFileSync(path.join(here, 'bundle.html'), 'utf8');
// split/join, not replace: the bundle contains `$&`/`$\`` regex literals that
// String.prototype.replace would interpret as replacement patterns.
fs.writeFileSync(path.join(serveDir, 'index.html'), page.split('<!--AGNT_BUNDLE-->').join(bundle));

// Minimal static server.
const server = http.createServer((req, res) => {
  const file = path.join(serveDir, req.url === '/' ? 'index.html' : req.url.split('?')[0]);
  fs.readFile(file, (err, buf) => {
    if (err) { res.writeHead(404); res.end('not found'); return; }
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(buf);
  });
});
await new Promise(r => server.listen(0, r));
const url = `http://localhost:${server.address().port}/index.html`;
console.log('serving', url);

const browser = await chromium.launch();

async function shot(name, drive) {
  const ctx = await browser.newContext({viewport: VIEW, recordVideo: {dir: vidDir, size: VIEW}});
  const pg = await ctx.newPage();
  pg.on('pageerror', e => console.log(`  [${name}] pageerror:`, e.message));
  await pg.goto(url, {waitUntil: 'load'});
  await pg.waitForFunction(() => window.__devtool && typeof window.__devtool === 'object', {timeout: 15000});
  await pg.waitForTimeout(800); // let UI settle / indicator mount
  try {
    await drive(pg);
  } catch (e) {
    console.log(`  [${name}] drive error:`, e.message);
  }
  await pg.waitForTimeout(700);
  await pg.screenshot({path: path.join(imgDir, `${name}.png`)});
  const video = pg.video();
  await ctx.close(); // flushes video
  if (video) {
    const vp = await video.path();
    fs.renameSync(vp, path.join(vidDir, `${name}.webm`));
  }
  console.log('  captured', name);
}

await shot('indicator', async (pg) => {
  await pg.evaluate(() => window.__devtool.indicator.show());
  await pg.waitForTimeout(300);
  await pg.evaluate(() => window.__devtool.indicator.togglePanel());
});

await shot('sketch-mode', async (pg) => {
  await pg.evaluate(() => window.__devtool.sketch.open());
  await pg.waitForTimeout(500);
  await pg.evaluate(() => window.__devtool.sketch.setTool && window.__devtool.sketch.setTool('rectangle'));
  // draw two rectangles with the mouse
  await pg.mouse.move(620, 260); await pg.mouse.down(); await pg.mouse.move(900, 380, {steps: 12}); await pg.mouse.up();
  await pg.waitForTimeout(200);
  await pg.evaluate(() => window.__devtool.sketch.setTool && window.__devtool.sketch.setTool('arrow'));
  await pg.mouse.move(640, 460); await pg.mouse.down(); await pg.mouse.move(880, 540, {steps: 12}); await pg.mouse.up();
});

await shot('design-mode', async (pg) => {
  await pg.evaluate(() => window.__devtool.design.start());
  await pg.waitForTimeout(400);
  // try to select a card element so the design panel populates
  try { await pg.click('.card', {timeout: 1500}); } catch {}
  await pg.waitForTimeout(400);
});

await shot('responsive-mode', async (pg) => {
  await pg.evaluate(() => window.__devtool.responsive.open());
  await pg.waitForTimeout(700);
  await pg.evaluate(() => window.__devtool.responsive.setWidth(414));
  await pg.waitForTimeout(600);
});

await browser.close();
server.close();
console.log('done');
