#!/usr/bin/env -S npx --yes tsx
// =============================================================================
// session_delete.ts — Delete an OpenCode session directly by ID
//
// Part of: .opencode/skills/auto-agents-system/scripts/
//
// Deletes a single session without issuing a stop signal first.  Use this for
// immediate removal regardless of the session's lifecycle state.
//
// By default the script refuses to delete a busy (actively processing) session
// to prevent accidental termination of in-flight work.  Pass --force to skip
// this check and delete regardless of running state.
//
// USAGE:
//   session_delete.ts --session-id ID [--force] [--server URL]
//
//   --session-id ID   Target session to delete
//   --force           Delete even if the session is currently busy
//   --server URL      OpenCode Server base URL (default: http://localhost:4096)
//
// OUTPUT (stdout): JSON object:
//   { session_id, title, deleted: boolean, message: string }
//
// EXIT CODES:
//   0 — session deleted (or already absent)
//   1 — deletion refused (busy + no --force), not found, or API error
//
// DEPENDENCIES: Node.js >= 18 (native fetch), npx tsx (TypeScript execution)
// =============================================================================
import { fileURLToPath } from 'node:url';
import {
  listSessions,
  getAllStatuses,
  deleteSession,
  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')) {
    printUsage();
    process.exit(0);
  }

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

  const force = hasFlag(rest, '--force');

  process.stderr.write(`Checking session ${sessionId}…\n`);

  // ── Look up the session ────────────────────────────────────────────────────
  const [sessions, statuses] = await Promise.all([
    listSessions(server),
    getAllStatuses(server),
  ]);

  const enriched = withStatuses(sessions, statuses);
  const target   = enriched.find(s => s.id === sessionId);

  if (!target) {
    const result = { session_id: sessionId, title: null, deleted: false, message: 'Session not found' };
    process.stdout.write(JSON.stringify(result, null, 2) + '\n');
    process.exit(1);
  }

  // ── Guard: refuse to delete a busy session unless --force ──────────────────
  if (target.status === 'busy' && !force) {
    const msg = `Session ${sessionId} is currently busy. Use --force to delete it anyway.`;
    process.stderr.write(`ERROR: ${msg}\n`);
    const result = {
      session_id: sessionId,
      title: target.title,
      deleted: false,
      message: msg,
    };
    process.stdout.write(JSON.stringify(result, null, 2) + '\n');
    process.exit(1);
  }

  if (target.status === 'busy' && force) {
    process.stderr.write(`NOTE: Session is busy but --force is set. Deleting anyway.\n`);
  }

  // ── Delete ─────────────────────────────────────────────────────────────────
  process.stderr.write(`Deleting session ${sessionId}…\n`);
  await deleteSession(server, sessionId);

  const result = {
    session_id: sessionId,
    title: target.title,
    deleted: true,
    message: `Session ${sessionId} deleted successfully`,
  };
  process.stdout.write(JSON.stringify(result, null, 2) + '\n');
}

function printUsage(): void {
  process.stderr.write(`\
Usage:
  session_delete.ts --session-id ID [OPTIONS]

REQUIRED:
  --session-id ID   Session ID to delete (e.g. ses_abc123)

OPTIONAL:
  --force           Delete even if the session is currently busy
  --server URL      OpenCode Server base URL (default: http://localhost:4096)
  -h, --help        Print this message and exit
`);
}

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