#!/usr/bin/env node
// Claude Code hook wrapper. Installed into ~/.claude/settings.json by
// lib/agent-hooks-installer.js. Reads Claude's hook JSON payload on stdin,
// forwards it to CTM's /hook/claude/<route> endpoint along with the CTM
// session id captured from CTM_SESSION_ID env at spawn time.
//
// Usage (from Claude Code's settings.json):
//   node <ctm>/bin/claude-hook.js <PORT> <ROUTE>
//   PORT  — CTM HTTP port (also available via $CTM_PORT if the parent set it)
//   ROUTE — start | stop | idle | menu
//
// Port of /tmp/clideck/bin/claude-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 || '',
    payload: stdin.trim() || undefined,
  });
  const req = http.request({
    hostname: 'localhost',
    port,
    path: `/hook/claude/${route}`,
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
    timeout: 2000,
  });
  req.on('error', () => {});
  req.end(body);
});
process.stdin.resume();
