/**
 * Conversation Learning Service
 *
 * Tracks unanswered questions and low-confidence KB matches to improve
 * the AI agent's knowledge base over time.
 */

import { convexMutation } from "@/lib/convex-client";
import { logger } from "@/lib/logger";

const KB_CONFIDENCE_THRESHOLD = 0.6;

interface ConversationTurnMetadata {
  organizationId: string;
  sector?: string;
  language: string;
  customerQuestion: string;
  kbUsed: boolean;
  kbConfidence: number;
  intent: string;
  escalatedToHuman: boolean;
}

/**
 * Analyze a conversation turn and track learning opportunities.
 * Called after each AI response in the webhook handler.
 */
export async function analyzeConversationTurn(
  metadata: ConversationTurnMetadata,
): Promise<void> {
  try {
    // Only track questions that the KB couldn't answer well
    if (
      metadata.intent === "company_query" &&
      (!metadata.kbUsed || metadata.kbConfidence < KB_CONFIDENCE_THRESHOLD)
    ) {
      await trackUnansweredQuestion(metadata);
    }

    // Also track escalated conversations
    if (metadata.escalatedToHuman) {
      await trackUnansweredQuestion({
        ...metadata,
        kbConfidence: 0, // Escalation = complete KB miss
      });
    }
  } catch (error) {
    // Non-blocking — learning failures shouldn't affect the conversation
    logger.error("[Learning] Failed to analyze turn", { error });
  }
}

async function trackUnansweredQuestion(
  metadata: ConversationTurnMetadata,
): Promise<void> {
  const normalized = metadata.customerQuestion
    .toLowerCase()
    .trim()
    .replace(/[?!.,;:]/g, "")
    .replace(/\s+/g, " ");

  if (normalized.length < 5) return; // Skip very short queries

  await convexMutation("whatsapp/mutations:trackUnansweredQuestion", {
    organizationId: metadata.organizationId,
    question: metadata.customerQuestion,
    normalizedQuestion: normalized,
    sector: metadata.sector,
    language: metadata.language,
  });

  logger.debug("[Learning] Tracked unanswered question", {
    organizationId: metadata.organizationId,
    question: metadata.customerQuestion.substring(0, 100),
    kbConfidence: metadata.kbConfidence,
  });
}

/**
 * Get the count of unanswered questions for an org (for dashboard display).
 */
export async function getUnansweredQuestionCount(
  organizationId: string,
): Promise<number> {
  try {
    const { convexQuery } = await import("@/lib/convex-client");
    const questions = await convexQuery(
      "whatsapp/queries:getUnansweredQuestions",
      {
        organizationId,
        status: "open",
        limit: 0, // Just need count
      },
    );
    return Array.isArray(questions) ? questions.length : 0;
  } catch {
    return 0;
  }
}
