/**
 * btw-sidebar.ts — Quick sidebar question without interrupting main reasoning.
 *
 * Emulates Claude Code's /btw behavior: user asks a short question,
 * gets a quick answer in a separate lightweight API call, main turn continues.
 *
 * Usage: /btw <question>
 */

import type { ExtensionAPI } from "@helios-agent/pi-coding-agent";
import { createRequire } from 'module';
const require = createRequire(import.meta.url);

export default function (pi: ExtensionAPI) {
  if (process.env.PI_SKIP_DEFERRED === '1') return;

  pi.registerCommand("btw", {
    description: "Ask a quick question without interrupting the current task",
    handler: async (args: string, ctx: any) => {
      const question = (args || "").trim();
      if (!question) {
        ctx.ui.notify("Usage: /btw <your question>", "warning");
        return;
      }

      ctx.ui.notify(`💬 btw: "${question}" — thinking...`, "info");

      try {
        // Use Pi's built-in agent dispatch with a lightweight model
        // The answer is displayed as a notification, not injected into main context
        const result = await new Promise<string>((resolve, reject) => {
          const { execFile } = require("child_process");
          // Find pi in PATH
          const piPath = (() => {
            try {
              const cmd = process.platform === 'win32' ? 'where.exe' : 'which';
              return require('child_process').execFileSync(cmd, ['pi'], { encoding: 'utf-8', stdio: 'pipe' }).trim().split('\n')[0].trim();
            } catch (e) {
              process.stderr.write(`[btw-sidebar.ts] operation failed: ${String(e)}\n`);
              return 'pi'; // fallback to PATH resolution
            }
          })();

          // Spawn a minimal pi subprocess with the question
          const child = execFile(
            piPath,
            [
              "--print",
              "--model", "anthropic/claude-haiku-4-5",
              "--system", "You are a helpful assistant. Answer briefly and directly in 1-3 sentences. No preamble.",
              question,
            ],
            {
              timeout: 30000,
              maxBuffer: 10 * 1024,
              env: { ...process.env, PI_SUBAGENT_DEPTH: "1" },
            },
            (err: any, stdout: string, stderr: string) => {
              if (err) {
                // Fallback: just show a simpler notification
                reject(err);
              } else {
                resolve(stdout.trim());
              }
            },
          );
        });

        ctx.ui.notify(`💬 btw answer:\n${result}`, "info");
      } catch (err: any) {
        // Graceful fallback — inject as a note the agent can see
        ctx.ui.notify(
          `💬 btw: Could not get a quick answer (${err.message}). ` +
          `The main reasoning is uninterrupted. Try asking in a new session.`,
          "warning",
        );
      }
    },
  });
}
