#!/usr/bin/env -S npx --yes tsx
// =============================================================================
// session_find_by_tag.ts — Find OpenCode sessions by exact tag match
//
// Part of: .opencode/skills/auto-agents-system/scripts/
//
// Lists all sessions and filters to those whose title starts with "[TAG]"
// where TAG exactly equals the provided --tag value.  Returns the matching
// sessions enriched with current busy/idle status and last-activity timestamp.
//
// Tag matching rule (mirrors async-agent-util):
//   A session title "[AUTO-IMP-SUP] implementor-sup" matches tag "AUTO-IMP-SUP"
//   but NOT "AUTO-IMP" or "AUTO-IMP-SUP-EXTRA".  The bracket-enclosed prefix
//   must be an exact string match.
//
// USAGE:
//   session_find_by_tag.ts --tag TAG [--server URL]
//
//   --tag TAG      Exact tag string to match (no brackets, e.g. AUTO-IMP-SUP)
//   --server URL   OpenCode Server base URL (default: http://localhost:4096)
//
// OUTPUT (stdout): JSON array of SessionWithStatus objects (may be empty).
//
// DEPENDENCIES: Node.js >= 18 (native fetch), npx tsx (TypeScript execution)
// =============================================================================
import { fileURLToPath } from 'node:url';
import {
  listSessions,
  getAllStatuses,
  withStatuses,
  extractTag,
  parseServerFlag,
  getFlag,
} 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_tag.ts --tag TAG [--server URL]\n');
    process.exit(0);
  }

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

  process.stderr.write(`Searching for sessions with exact tag [${tag}]…\n`);

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

  const enriched = withStatuses(sessions, statuses);

  // Exact match: extractTag(title) must equal tag exactly
  const matched = enriched.filter(s => extractTag(s.title) === tag);

  process.stderr.write(`Found ${matched.length}/${sessions.length} session(s) with tag [${tag}].\n`);
  process.stdout.write(JSON.stringify(matched, 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);
  });
}
