#!/usr/bin/env -S npx --yes tsx
// =============================================================================
// session_list.ts — List all OpenCode sessions with their current statuses
//
// Part of: .opencode/skills/auto-agents-system/scripts/
//
// Fetches all sessions from the OpenCode Server and enriches each one with
// its current busy/idle status and last-activity timestamp.
//
// USAGE:
//   session_list.ts [--server URL]
//
// OUTPUT (stdout): JSON array of SessionWithStatus objects sorted by
//   last_active descending (most recently active first).
//
// DEPENDENCIES: Node.js >= 18 (native fetch), npx tsx (TypeScript execution)
// =============================================================================
import { fileURLToPath } from 'node:url';
import {
  listSessions,
  getAllStatuses,
  withStatuses,
  parseServerFlag,
  type SessionWithStatus,
} from './session_api.ts';

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

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

  // Handle --help
  if (rest.includes('-h') || rest.includes('--help')) {
    process.stderr.write('Usage: session_list.ts [--server URL]\n');
    process.exit(0);
  }

  process.stderr.write(`Fetching sessions from ${server}…\n`);

  const [sessions, statuses] = await Promise.all([
    listSessions(server),
    getAllStatuses(server),
  ]);

  const enriched: SessionWithStatus[] = withStatuses(sessions, statuses)
    .sort((a, b) => b.last_active - a.last_active);

  process.stderr.write(`Found ${enriched.length} session(s).\n`);
  process.stdout.write(JSON.stringify(enriched, null, 2) + '\n');
}

// ─────────────────────────────────────────────────────────────────────────────
// 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);
  });
}
