#!/usr/bin/env -S npx --yes tsx
// =============================================================================
// session_find_by_prefix.ts — Find OpenCode sessions by tag prefix
//
// Part of: .opencode/skills/auto-agents-system/scripts/
//
// Lists all sessions and filters to those whose tag starts with the given
// prefix.  Returns the matching sessions enriched with current busy/idle
// status and last-activity timestamp.
//
// Prefix matching rule (mirrors async-agent-util find_by_prefix):
//   The check is: sessionTag.startsWith(prefix)
//   e.g. prefix "AUTO-IMP" matches tags "AUTO-IMP-001", "AUTO-IMP-SUP",
//   "AUTO-IMP-ISSUE-42", but NOT "AUTO-IMPL" or "AUTO" alone.
//
// USAGE:
//   session_find_by_prefix.ts --prefix PREFIX [--exclude-supervisor] \
//     [--status busy|idle|all] [--server URL]
//
//   --prefix PREFIX        Tag prefix to match (no brackets, e.g. AUTO-IMP)
//   --exclude-supervisor   Exclude sessions whose tag ends with "-SUP"
//   --status STATUS        Filter by session status: "busy", "idle", or "all"
//                          (default: "all" — no status filtering)
//   --server URL           OpenCode Server base URL (default: http://localhost:4096)
//
// OUTPUT (stdout): JSON array of SessionWithStatus objects (may be empty).
//   Results are 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,
  getFlag,
  hasFlag,
} from './session_api.ts';

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

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

  if (rest.includes('-h') || rest.includes('--help')) {
    process.stderr.write(
      'Usage: session_find_by_prefix.ts --prefix PREFIX [--exclude-supervisor] [--status busy|idle|all] [--server URL]\n',
    );
    process.exit(0);
  }

  const prefix = getFlag(rest, '--prefix');
  if (!prefix) { process.stderr.write('ERROR: --prefix is required\n'); process.exit(1); }

  const excludeSupervisor = hasFlag(rest, '--exclude-supervisor');

  const statusFilter = getFlag(rest, '--status') ?? 'all';
  if (statusFilter !== 'busy' && statusFilter !== 'idle' && statusFilter !== 'all') {
    process.stderr.write(`ERROR: --status must be "busy", "idle", or "all", got "${statusFilter}"\n`);
    process.exit(1);
  }

  const parts: string[] = [];
  if (excludeSupervisor) parts.push('excluding -SUP sessions');
  if (statusFilter !== 'all') parts.push(`${statusFilter} only`);
  const qualifier = parts.length > 0 ? ` (${parts.join(', ')})` : '';

  process.stderr.write(
    `Searching for sessions with tag prefix "${prefix}"${qualifier}…\n`,
  );

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

  let enriched = withStatuses(sessions, statuses);

  // Prefix match: session tag must start with the given prefix string
  enriched = enriched.filter(s => s.tag !== null && s.tag.startsWith(prefix));

  // Optionally exclude supervisor sessions (tag ending in "-SUP")
  if (excludeSupervisor) {
    enriched = enriched.filter(s => !s.tag?.endsWith('-SUP'));
  }

  // Optionally filter by status
  if (statusFilter !== 'all') {
    enriched = enriched.filter(s => s.status === statusFilter);
  }

  // Sort most-recently-active first
  enriched.sort((a, b) => b.last_active - a.last_active);

  process.stderr.write(`Found ${enriched.length}/${sessions.length} session(s) matching prefix "${prefix}".\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);
  });
}
