const { chromium } = require('playwright');
const fs = require('node:fs');
const path = require('node:path');
const readline = require('node:readline/promises');
const { stdin, stdout } = require('node:process');

async function run() {
  const startUrl = process.argv[2] || 'about:blank';
  const tracesDir = path.join(process.cwd(), 'traces');
  fs.mkdirSync(tracesDir, { recursive: true });

  const traceName = `manual-trace-${new Date().toISOString().replace(/[.:]/g, '-')}.zip`;
  const tracePath = path.join(tracesDir, traceName);

  const browser = await chromium.launch({ headless: false });
  const context = await browser.newContext();

  try {
    await context.tracing.start({ screenshots: true, snapshots: true, sources: true });

    const page = await context.newPage();
    await page.goto(startUrl);

    console.log(`Tracing started. Navigate manually in the opened browser.`);
    console.log(`Start URL: ${startUrl}`);

    const prompt = readline.createInterface({ input: stdin, output: stdout });
    await prompt.question('Press Enter here to stop tracing and save the trace file...');
    prompt.close();

    await context.tracing.stop({ path: tracePath });
    console.log(`Trace saved: ${tracePath}`);
  } finally {
    await context.close();
    await browser.close();
  }
}

run().catch((error) => {
  console.error('Failed to capture manual trace:', error);
  process.exitCode = 1;
});