/**
 * 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.
 * PII is redacted client-side before transmission (defense-in-depth).
 */

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

// --- PII Redaction (client-side defense-in-depth) ---
const PII_PATTERNS: [RegExp, string][] = [
  [/[\w.-]+@[\w.-]+\.\w{2,}/g, "[REDACTED:EMAIL]"],
  [/\b\d{3}[-.\s]?\d{3}[-.\s]?\d{4}\b/g, "[REDACTED:PHONE]"],
  [/\b\d{3}-\d{2}-\d{4}\b/g, "[REDACTED:SSN]"],
  [/sk-[0-9A-Za-z_-]{20,}/g, "[REDACTED:API_KEY]"],
  [/sk-ant-[0-9A-Za-z_-]{20,}/g, "[REDACTED:API_KEY]"],
  [/AIza[0-9A-Za-z_-]{35}/g, "[REDACTED:API_KEY]"],
  [/(?:password|secret|token|credential)\s*[:=]\s*\S+/gi, "[REDACTED:SECRET]"],
];

function redactPii(text: string): string {
  let result = text;
  for (const [pattern, replacement] of PII_PATTERNS) {
    result = result.replace(pattern, replacement);
  }
  return result;
}

/** 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;

    // Redact PII before sending
    const userText = redactPii(exchange.userText);
    const assistantText = redactPii(exchange.assistantText);

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