#!/usr/bin/env bun
// todo-autocapture — UserPromptSubmit hook: turn every request-bearing owner
// prompt into a pending task, so recording an ask is never an agent's judgment
// call. Classifier is a closed acknowledgement-token list and fails closed:
// anything not made entirely of pure-ack words becomes a task.
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
  appendLedger,
  createTask,
  fingerprint,
  gateDisabled,
  isRequest,
  readLedger,
  tasksDir,
} from './lib/task-store.mjs';

const CLI = path.join(path.dirname(fileURLToPath(import.meta.url)), 'todo-tasks.mjs');

function emit(text) {
  console.log(
    JSON.stringify({
      hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: text },
    })
  );
}

function subjectOf(prompt) {
  const firstLine = prompt.trim().split('\n').find((l) => l.trim()) || prompt.trim();
  const s = firstLine.trim();
  return s.length > 100 ? `${s.slice(0, 97)}...` : s;
}

function main() {
  if (gateDisabled()) return;
  let inp = {};
  try {
    inp = JSON.parse(fs.readFileSync(0, 'utf8'));
  } catch {
    return;
  }
  const prompt = typeof inp.prompt === 'string' ? inp.prompt : '';
  if (!prompt.trim()) return;
  if (!isRequest(prompt)) return;

  const sessionId = inp.session_id || '';
  const dir = tasksDir(sessionId);
  const fp = fingerprint(`${sessionId}\n${prompt}`);

  try {
    if (readLedger(dir).some((e) => e.event === 'capture' && e.fingerprint === fp)) return;
    const task = createTask(dir, {
      subject: subjectOf(prompt),
      description: prompt,
      activeForm: `Addressing: ${subjectOf(prompt).slice(0, 80)}`,
      metadata: { autoCaptured: 'true', sessionId: String(sessionId), fingerprint: fp },
    });
    appendLedger(dir, {
      event: 'capture',
      id: task.id,
      fingerprint: fp,
      subject: task.subject,
      at: new Date().toISOString(),
    });
    const dismissed = readLedger(dir).filter((e) => e.event === 'dismiss').length;
    emit(
      `todo-autocapture: this prompt was recorded as task #${task.id} (status pending). ` +
        `Before any Edit/Write you must have a task in_progress — TaskUpdate #${task.id} to in_progress, ` +
        `or from Bash: bun ${CLI} start ${task.id}. ` +
        `If it needs no work: bun ${CLI} dismiss ${task.id} "<reason>". ` +
        `Stop is blocked while it is still pending. Dismissed so far this session: ${dismissed}.`
    );
  } catch (e) {
    emit(
      `todo-autocapture: FAILED to record this prompt as a task (${e.message}). ` +
        `Register it yourself with TaskCreate now — the ask must not be dropped.`
    );
  }
}

main();
process.exit(0);
