#!/usr/bin/env node
// Gemini CLI hook wrapper. Installed into ~/.gemini/settings.json by
// lib/agent-hooks-installer.js. Reads Gemini's hook JSON payload on stdin,
// forwards it to CTM's /hook/gemini/<route> endpoint.
//
// Usage:
//   node <ctm>/bin/gemini-hook.js <PORT> <ROUTE>
//   ROUTE — start | stop | menu
//
// Gemini often drops OTEL_RESOURCE_ATTRIBUTES, so we lean on CTM_SESSION_ID +
// GEMINI_SESSION_ID fallback for correlation. Port of /tmp/clideck/bin/gemini-hook.js.

const http = require('http');

const port = parseInt(process.argv[2], 10) || parseInt(process.env.CTM_PORT, 10);
const route = process.argv[3];
if (!port || !route) process.exit(0);

let stdin = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', (chunk) => { stdin += chunk; });
process.stdin.on('end', () => {
  let hook = {};
  try { hook = stdin ? JSON.parse(stdin) : {}; } catch {}
  const body = JSON.stringify({
    ctm_id: process.env.CTM_SESSION_ID || '',
    session_id: hook.session_id || process.env.GEMINI_SESSION_ID || '',
    payload: stdin.trim() || undefined,
  });
  const req = http.request({
    hostname: 'localhost',
    port,
    path: `/hook/gemini/${route}`,
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
    timeout: 2000,
  });
  req.on('error', () => {});
  req.end(body);
});
process.stdin.resume();
