#!/usr/bin/env tsx
/**
 * Cockroach CLI — Rainmaker QA Crawler
 *
 * Usage:
 *   npx tsx src/cli.ts [options]
 *   npm run cockroach -- [options]
 *
 * Options:
 *   --baseUrl=<url>      Target URL (default: https://rainmakersports.app)
 *   --loggedOutOnly       Only test logged-out flows
 *   --fullCrawl           Full depth crawl (all routes)
 *   --mobileOnly          Only mobile viewports (default)
 *   --maxActions=<n>      Max click actions per combo (default: 200)
 *   --maxDepth=<n>        Max crawl depth (default: 4)
 *   --headed              Show browser windows
 *   --noTrace             Disable Playwright tracing
 */

import { Crawler } from './crawler.js';
import { ReportGenerator } from './report-generator.js';
import { DEFAULT_OPTIONS, type CockroachOptions } from './config.js';
import * as path from 'path';

function parseArgs(): Partial<CockroachOptions> {
  const args = process.argv.slice(2);
  const opts: Record<string, any> = {};

  for (const arg of args) {
    if (arg.startsWith('--baseUrl=')) opts.baseUrl = arg.split('=')[1];
    else if (arg === '--loggedOutOnly') opts.loggedOutOnly = true;
    else if (arg === '--fullCrawl') opts.fullCrawl = true;
    else if (arg === '--mobileOnly') opts.mobileOnly = true;
    else if (arg.startsWith('--maxActions=')) opts.maxActions = parseInt(arg.split('=')[1], 10);
    else if (arg.startsWith('--maxDepth=')) opts.maxDepth = parseInt(arg.split('=')[1], 10);
    else if (arg === '--headed') opts.headless = false;
    else if (arg === '--noTrace') opts.tracing = false;
  }

  return opts;
}

async function main() {
  const overrides = parseArgs();
  const options: CockroachOptions = { ...DEFAULT_OPTIONS, ...overrides };

  // Resolve paths relative to project root
  const projectRoot = path.resolve(import.meta.dirname || __dirname, '..');
  options.outputDir = path.resolve(projectRoot, options.outputDir);
  options.screenshotDir = path.resolve(projectRoot, options.screenshotDir);

  console.log('='.repeat(60));
  console.log('  COCKROACH — Rainmaker QA Crawler');
  console.log('='.repeat(60));
  console.log(`  Target:     ${options.baseUrl}`);
  console.log(`  Mode:       ${options.loggedOutOnly ? 'Logged-out only' : 'Full'}`);
  console.log(`  Viewports:  ${options.mobileOnly ? 'Mobile only' : 'All'}`);
  console.log(`  Max actions: ${options.maxActions} per combo`);
  console.log(`  Max depth:   ${options.maxDepth}`);
  console.log(`  Tracing:     ${options.tracing ? 'ON' : 'OFF'}`);
  console.log(`  Output:      ${options.outputDir}`);
  console.log('='.repeat(60));

  const crawler = new Crawler(options);
  const results = await crawler.run();

  console.log('\n' + '='.repeat(60));
  console.log('  Generating report...');

  const reporter = new ReportGenerator(options.outputDir);
  const { reportPath, bugsPath } = reporter.generate(results);

  // Summary
  const totalBugs = results.reduce((s, r) => s + r.bugs.length, 0);
  const uniqueBugs = new Set(results.flatMap((r) => r.bugs.map((b) => `${b.category}|${b.title}|${b.url}`))).size;
  const p0Count = results.flatMap((r) => r.bugs).filter((b) => b.severity === 'P0').length;

  console.log('='.repeat(60));
  console.log(`  COCKROACH REPORT`);
  console.log('='.repeat(60));
  console.log(`  Combos tested:  ${results.length}`);
  console.log(`  Total bugs:     ${totalBugs} (${uniqueBugs} unique)`);
  console.log(`  P0 (critical):  ${p0Count}`);
  console.log(`  Report:         ${reportPath}`);
  console.log(`  Bugs JSON:      ${bugsPath}`);
  console.log('='.repeat(60));

  // Exit with error code if P0 bugs found
  if (p0Count > 0) {
    console.log(`\n  !! ${p0Count} P0 bugs found — see report for details\n`);
    process.exit(1);
  }

  process.exit(0);
}

main().catch((err) => {
  console.error('Cockroach fatal error:', err);
  process.exit(2);
});
