const { run: runStats } = require("./caveman-stats");

function readStdin() {
  return new Promise((resolve) => {
    let data = "";
    process.stdin.setEncoding("utf8");
    process.stdin.on("data", (chunk) => {
      data += chunk;
    });
    process.stdin.on("end", () => resolve(data));
  });
}

function respond(payload) {
  process.stdout.write(`${JSON.stringify(payload)}\n`);
}

async function main() {
  const raw = await readStdin();
  const input = raw.trim() ? JSON.parse(raw) : {};
  const prompt = String(input.prompt || input.userPrompt || "").trim();

  if (/^\/caveman-stats(?:\s|$)/i.test(prompt)) {
    respond({
      decision: "block",
      reason: runStats(input),
    });
    return;
  }

  respond({});
}

main().catch((error) => {
  respond({
    decision: "block",
    reason: `caveman hook failed: ${error.message}`,
  });
});

