/**
 * Auto-capture hook — saves conversation turns to PULSE brain after each agent response.
 *
 * Hooks into `agent_end` to extract knowledge from the interaction.
 * Non-blocking — capture failures never break the session.
 */

import type { PulseClient } from "../client.js";

/** Extract the last user+assistant exchange from messages. */
function getLastExchange(messages: any[]): {
  userText: string;
  assistantText: string;
} | null {
  if (!messages?.length) return null;

  let lastUser = "";
  let lastAssistant = "";

  // Walk backwards to find the last exchange
  for (let i = messages.length - 1; i >= 0; i--) {
    const msg = messages[i];
    const content =
      typeof msg.content === "string"
        ? msg.content
        : JSON.stringify(msg.content);

    if (msg.role === "assistant" && !lastAssistant) {
      lastAssistant = content;
    } else if (msg.role === "user" && !lastUser && lastAssistant) {
      lastUser = content;
      break;
    }
  }

  if (!lastUser || !lastAssistant) return null;
  return { userText: lastUser, assistantText: lastAssistant };
}

/** Create the agent_end handler for auto-capture. */
export function createAutoCaptureHandler(client: PulseClient) {
  return async (event: any) => {
    // Only capture successful turns
    if (!event.success) return;

    const exchange = getLastExchange(event.messages);
    if (!exchange) return;

    // Non-blocking fire-and-forget
    client
      .capture(exchange.userText, exchange.assistantText)
      .catch(() => {
        // Silently fail — never break the session
      });
  };
}
