const { chromium } = require('playwright');
const http = require('http');
const fs = require('fs');
const path = require('path');

const PORT = 9876;
const DEMO_HTML = path.join(__dirname, '../product/site/tiktok-demo.html');

// Simple static server
const server = http.createServer((req, res) => {
  const filePath = req.url === '/' ? DEMO_HTML : path.join(__dirname, '../product/site', req.url);
  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.writeHead(404); res.end('Not found'); return;
    }
    const ext = path.extname(filePath);
    const ct = ext === '.html' ? 'text/html' : ext === '.js' ? 'application/javascript' : ext === '.css' ? 'text/css' : 'application/octet-stream';
    res.writeHead(200, { 'Content-Type': ct });
    res.end(data);
  });
});

async function record() {
  server.listen(PORT, '127.0.0.1', async () => {
    console.log(`Server running on http://127.0.0.1:${PORT}`);

    const outDir = path.join(__dirname, '../product/site');
    const browser = await chromium.launch({ headless: true });
    const context = await browser.newContext({
      viewport: { width: 1280, height: 800 },
      recordVideo: { dir: outDir, size: { width: 1280, height: 800 } }
    });
    const page = await context.newPage();

    await page.goto(`http://127.0.0.1:${PORT}/tiktok-demo.html`, { waitUntil: 'networkidle' });
    console.log('Page loaded, recording demo...');

    // Wait for the full demo to complete (~2.5 minutes)
    await page.waitForTimeout(155000);

    await context.close();
    await browser.close();
    server.close();
    console.log('Recording complete');
  });
}

record().catch(err => {
  console.error(err);
  server.close();
  process.exit(1);
});
