#!/usr/bin/env -S npx --yes tsx
// =============================================================================
// session_wait_till_supervisor_idle.ts — Block until a supervisor slot opens
//
// Part of: .opencode/skills/auto-agents-system/scripts/
//
// Convenience wrapper around session_wait_till_idle.ts for the supervisor case.
// Blocks until the number of busy supervisor sessions (tags ending in "-SUP")
// drops below the expected supervisor count.
//
// This is useful when a caller needs to wait for at least one supervisor to
// finish before launching or re-launching a supervisor.
//
// USAGE:
//   session_wait_till_supervisor_idle.ts \
//     --expected-supervisors N --timeout SECONDS [--server URL]
//
//   --expected-supervisors N   Positive integer; the number of supervisors
//                              expected to be running.  The script blocks while
//                              the busy supervisor count >= this value.
//   --timeout SECONDS          Positive integer; maximum seconds to block.
//   --server URL               OpenCode Server base URL (default: http://localhost:4096)
//
// OUTPUT (stdout): JSON object — same schema as session_wait_till_idle.ts
//
// EXIT CODE: Always 0.  The `timed_out` field indicates whether the timeout
//   was reached before the condition was satisfied.
//
// DEPENDENCIES: Node.js >= 18 (native fetch), npx tsx (TypeScript execution)
// =============================================================================
import { fileURLToPath } from 'node:url';
import { parseServerFlag, getFlag } from './session_api.ts';
import { waitTillIdle } from './session_wait_till_idle.ts';

// ─────────────────────────────────────────────────────────────────────────────
// MAIN
// ─────────────────────────────────────────────────────────────────────────────

async function main(): Promise<void> {
  const { server, rest } = parseServerFlag(process.argv);

  if (rest.includes('-h') || rest.includes('--help')) {
    printUsage();
    process.exit(0);
  }

  // Parse expected-supervisors
  const rawExpected = getFlag(rest, '--expected-supervisors');
  if (!rawExpected) {
    process.stderr.write('ERROR: --expected-supervisors is required\n');
    process.exit(1);
  }
  const expectedSupervisors = Number(rawExpected);
  if (!Number.isInteger(expectedSupervisors) || expectedSupervisors <= 0) {
    process.stderr.write(
      `ERROR: --expected-supervisors must be a positive integer, got "${rawExpected}"\n`,
    );
    process.exit(1);
  }

  // Parse timeout
  const rawTimeout = getFlag(rest, '--timeout');
  if (!rawTimeout) {
    process.stderr.write('ERROR: --timeout is required\n');
    process.exit(1);
  }
  const timeoutSeconds = Number(rawTimeout);
  if (!Number.isInteger(timeoutSeconds) || timeoutSeconds <= 0) {
    process.stderr.write(
      `ERROR: --timeout must be a positive integer, got "${rawTimeout}"\n`,
    );
    process.exit(1);
  }

  process.stderr.write(
    `Waiting for supervisor pool to have fewer than ${expectedSupervisors} busy session(s) ` +
    `— timeout: ${timeoutSeconds}s\n`,
  );

  const result = await waitTillIdle({
    server,
    mode: 'supervisors',
    maxPoolSize: expectedSupervisors,
    timeoutSeconds,
  });

  if (result.timed_out) {
    process.stderr.write(
      `Timed out after ${result.elapsed_seconds}s — ${result.busy_count} busy supervisor(s) ` +
      `still >= expected ${result.max_pool_size}\n`,
    );
  } else {
    process.stderr.write(
      `Condition met after ${result.elapsed_seconds}s — ${result.busy_count} busy supervisor(s) ` +
      `< expected ${result.max_pool_size}\n`,
    );
  }

  process.stdout.write(JSON.stringify(result, null, 2) + '\n');
}

function printUsage(): void {
  process.stderr.write(`\
Usage:
  session_wait_till_supervisor_idle.ts \\
    --expected-supervisors N --timeout SECONDS [--server URL]

REQUIRED:
  --expected-supervisors N   Positive integer; block while the number of busy
                             supervisor sessions (tags ending in "-SUP") >= N
  --timeout SECONDS          Positive integer; maximum seconds to block

OPTIONAL:
  --server URL               OpenCode Server base URL (default: http://localhost:4096)
  -h, --help                 Print this message and exit

This script counts all sessions whose tag ends in "-SUP" and have a "busy"
status.  It blocks while that count >= the expected supervisor count, and
returns as soon as the count drops below or the timeout is reached.
`);
}

// ─────────────────────────────────────────────────────────────────────────────
// CLI ENTRY POINT
// ─────────────────────────────────────────────────────────────────────────────

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  main().catch((err: unknown) => {
    process.stderr.write(`ERROR: ${err instanceof Error ? err.message : String(err)}\n`);
    process.exit(1);
  });
}
