import { chromium } from 'playwright';
import { writeFileSync } from 'node:fs';

const url = process.argv[2];
if (!url) {
  console.error('Usage: node extract.mjs <url>');
  process.exit(1);
}

const browser = await chromium.launch({ headless: true });
const page = await browser.newPage();
const errors = [];
page.on('console', (m) => {
  if (m.type() === 'error') errors.push(m.text());
});

await page.goto(url, { waitUntil: 'networkidle', timeout: 90000 });
const title = await page.title();

let source = null;
try {
  await page.waitForFunction(() => window.__AXHUB_ANNOTATION_SOURCE__, { timeout: 30000 });
  source = await page.evaluate(() => window.__AXHUB_ANNOTATION_SOURCE__);
} catch {
  // fall through
}

const out = { title, errors, source };
writeFileSync('output.json', JSON.stringify(out, null, 2));
console.log(
  JSON.stringify(
    {
      title,
      errorCount: errors.length,
      hasSource: !!source,
      nodeCount: source?.nodes?.length ?? 0,
      directoryNodeCount: source?.directory?.nodes?.length ?? 0,
      sourceRoot: source?.source?.root ?? null,
      sourceManifest: source?.source?.manifest ?? null,
    },
    null,
    2
  )
);

await browser.close();
