import type { RequestRow } from "./requests-store";

export async function announceRequest(row: RequestRow, deps: { send(channel: string, text: string): Promise<string> }): Promise<void> {
  await deps.send(row.project, `New request #${row.id}: ${row.title}\nReply to this thread to steer it.`);
}

/** Notify the owner exactly when a row enters the owner-decision state. */
export async function announceOwnerBlock(row: RequestRow, deps: { send(channel: string, text: string, needsAnswer?: boolean): Promise<string> }): Promise<void> {
  await deps.send("Overdeck", `Blocked — needs you: ${row.title}\n${row.detail ?? ""}`, true);
}

export async function sendRequestAnnouncement(channel: string, text: string, needsAnswer = false): Promise<string> {
  const process = Bun.spawn(["botmaster", "--channel", channel, ...(needsAnswer ? ["--needs-answer"] : []), "--text", text], { stdout: "pipe", stderr: "pipe" });
  const [exitCode, stdout, stderr] = await Promise.all([
    process.exited,
    new Response(process.stdout).text(),
    new Response(process.stderr).text(),
  ]);
  if (exitCode !== 0) throw new Error(`botmaster exited ${exitCode}: ${stderr.trim()}`);
  return stdout.trim();
}

/** Botmaster is optional infrastructure; a missing configuration never blocks work. */
export async function notifyOwnerBlock(row: RequestRow): Promise<void> {
  try {
    await announceOwnerBlock(row, { send: sendRequestAnnouncement });
  } catch {
    // Deliberately silent: the request row remains the durable owner surface.
  }
}
