#!/usr/bin/env -S npx --yes tsx
// =============================================================================
// session_prompt.ts — Send a prompt to an EXISTING OpenCode session
//
// Part of: .opencode/skills/auto-agents-system/scripts/
//
// Sends a prompt to a session that already exists, without creating a new one.
// This is the script for the "send continue" pattern: nudging an idle-but-healthy
// session back into operation, or sending any other follow-up message to an
// ongoing session.
//
// Unlike session_start.ts (which creates a new session), this script requires
// the target session to already exist and sends a prompt to it via
// POST /session/{id}/prompt_async (fire-and-forget).
//
// USAGE:
//   session_prompt.ts --session-id ID --agent AGENT \
//     (--prompt TEXT | --prompt-file PATH) [--server URL]
//
//   --session-id ID   Target session ID (e.g. ses_abc123)
//   --agent AGENT     Agent name to invoke in the session (e.g. pr-merge-supervisor)
//   --prompt TEXT     Prompt text to send (suitable for short prompts like "continue")
//   --prompt-file PATH  Path to a file containing the prompt text; preferred for
//                     long or multi-line prompts to avoid shell-escaping issues
//   --server URL      OpenCode Server base URL (default: http://localhost:4096)
//
// OUTPUT (stdout): JSON object:
//   { session_id, agent, sent: true, message }
//
// EXIT CODES:
//   0 — prompt sent successfully (server returned 204)
//   1 — session not found or API error
//
// DEPENDENCIES: Node.js >= 18 (native fetch), npx tsx (TypeScript execution)
// =============================================================================
import { fileURLToPath } from 'node:url';
import { readFileSync } from 'node:fs';
import {
  promptAsync,
  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')) {
    printUsage();
    process.exit(0);
  }

  const sessionId  = getFlag(rest, '--session-id');
  const agentName  = getFlag(rest, '--agent');
  const promptText = getFlag(rest, '--prompt');
  const promptFile = getFlag(rest, '--prompt-file');

  if (!sessionId)  { process.stderr.write('ERROR: --session-id is required\n'); process.exit(1); }
  if (!agentName)  { process.stderr.write('ERROR: --agent is required\n');      process.exit(1); }
  if (!promptText && !promptFile) {
    process.stderr.write('ERROR: one of --prompt or --prompt-file is required\n');
    process.exit(1);
  }

  // Resolve the final prompt string
  let finalPrompt: string;
  if (promptFile) {
    try {
      finalPrompt = readFileSync(promptFile, 'utf-8');
    } catch (e) {
      process.stderr.write(`ERROR: Could not read prompt file "${promptFile}": ${e}\n`);
      process.exit(1);
    }
  } else {
    finalPrompt = promptText!;
  }

  process.stderr.write(`Sending prompt to session ${sessionId} (agent: ${agentName})…\n`);

  await promptAsync(server, sessionId, agentName, finalPrompt);

  process.stderr.write(`Prompt sent (prompt_async returned 204).\n`);

  const result = {
    session_id: sessionId,
    agent: agentName,
    sent: true,
    message: `Prompt sent to session ${sessionId} via agent "${agentName}"`,
  };
  process.stdout.write(JSON.stringify(result, null, 2) + '\n');
}

function printUsage(): void {
  process.stderr.write(`\
Usage:
  session_prompt.ts --session-id ID --agent AGENT (--prompt TEXT | --prompt-file PATH) [OPTIONS]

REQUIRED:
  --session-id ID   Target session ID (e.g. ses_abc123)
  --agent AGENT     Agent name to invoke in the session
  --prompt TEXT     Short prompt text to send (e.g. "continue")
  --prompt-file PATH  Path to file containing prompt text (for long prompts)

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

COMMON USE CASE — nudge an idle supervisor back into operation:
  session_prompt.ts --session-id ses_abc123 --agent pr-merge-supervisor --prompt "continue"
`);
}

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