/**
 * GET /api/onboarding/detect-cli
 *
 * Async, parallel `which <name> && <name> --version` for claude/codex/aider.
 * Returns whichever ones are present. Fast — each probe capped at ~1.5s
 * with explicit abort, then all 3 race in parallel (Promise.all).
 *
 * Split out from the main onboarding GET so Dashboard mount stays
 * instant (3 × execSync was blocking the Node event loop up to 15s on
 * misses, which froze every other API on the same worker).
 *
 * Wizard calls this when the drawer opens — by which time the user
 * has already seen the rest of their config load.
 */

import { NextResponse } from 'next/server';
import { exec } from 'node:child_process';
import { promisify } from 'node:util';

const execAsync = promisify(exec);

async function probe(name: string): Promise<{ name: string; path: string; version: string } | null> {
  try {
    const which = await execAsync(`which ${name}`, { timeout: 800 });
    const path = which.stdout.trim();
    if (!path) return null;
    let version = '';
    try {
      const v = await execAsync(`${path} --version`, { timeout: 1500 });
      const out = v.stdout.trim();
      const m = out.match(/v?(\d+\.\d+\.\d+)/);
      version = m ? m[1] : out.slice(0, 30);
    } catch { /* optional */ }
    return { name, path, version };
  } catch {
    return null;
  }
}

export async function GET() {
  const probes = await Promise.all(['claude', 'codex', 'aider'].map(probe));
  return NextResponse.json({
    ok: true,
    detected: probes.filter((x): x is { name: string; path: string; version: string } => x != null),
  });
}
