#!/usr/bin/env node
// Codex notify-hook wrapper. Codex calls this when a turn completes (via the
// [notify] block in ~/.codex/config.toml installed by lib/agent-hooks-installer.js).
// The payload on stdin is a JSON object from Codex; we forward the thread-id
// to CTM's /hook/codex/stop endpoint so the telemetry-receiver can arm the
// pending-stop state (committed on the next response.completed).
//
// Usage:
//   node <ctm>/bin/codex-notify.js <PORT> stop
//
// Matches the shape of /tmp/clideck/server.js:110 (/hook/codex/stop handler)
// and of codex-config.js:48-51 (the [notify] block patched into Codex config).

const http = require('http');

const port = parseInt(process.argv[2], 10) || parseInt(process.env.CTM_PORT, 10);
const route = process.argv[3] || 'stop';
if (!port) 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({
    clideck_id: process.env.CTM_SESSION_ID || '',  // kept for cross-compat with CliDeck-style receivers
    ctm_id: process.env.CTM_SESSION_ID || '',
    'thread-id': hook['thread-id'] || hook.session_id || '',
    session_id: hook.session_id || hook['thread-id'] || '',
    payload: stdin.trim() || undefined,
  });
  const req = http.request({
    hostname: 'localhost',
    port,
    path: `/hook/codex/${route}`,
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
    timeout: 2000,
  });
  req.on('error', () => {});
  req.end(body);
});
process.stdin.resume();
