/**
 * Public assistant engine.
 *
 * Two modes, one interface:
 *  - **Grounded** — when `AI_API_KEY` is set, the question plus the matched
 *    knowledge entries are sent to an OpenAI-compatible chat endpoint.
 *  - **Offline** — with no credentials, the assistant answers directly from the
 *    knowledge base. The page therefore always works, and enabling a real model
 *    is a config change rather than a code change.
 *
 * The knowledge base itself is admin-managed (see `lib/queries/knowledge`), so
 * answers can be corrected from the console without a redeploy.
 */

import { env } from "@/lib/env";
import { TECHC } from "@/lib/techc";
import { rankEntries, salientTerms, type KnowledgeMatch } from "@/lib/ai/knowledge";
import { loadRankableEntries, recordUnanswered } from "@/lib/queries/knowledge";

export interface ChatTurn {
  role: "user" | "assistant";
  content: string;
}

export interface ChatReply {
  answer: string;
  /** Knowledge entries the answer was drawn from. */
  sources: { id: string; label: string }[];
  /** How the answer was produced, surfaced in the UI as a provenance badge. */
  mode: "ai" | "kb";
}

const MAX_HISTORY_TURNS = 6;
const MAX_QUESTION_CHARS = 600;

function sourcesOf(matches: KnowledgeMatch[]): { id: string; label: string }[] {
  return matches.map((m) => ({ id: m.entry.id, label: m.entry.topic }));
}

function offlineReply(matches: KnowledgeMatch[]): ChatReply {
  if (matches.length === 0) {
    return {
      mode: "kb",
      sources: [],
      answer:
        "Maaf, saya belum punya jawaban untuk pertanyaan itu. Saya paling paham soal program kursus, materi, biaya, jenjang kelas, jadwal, lokasi, pendaftaran, prestasi, dan kerja sama sekolah TECH-C.\n\nUntuk pertanyaan lain, silakan hubungi tim kami langsung via WhatsApp " +
        TECHC.phone +
        ".",
    };
  }

  // Up to two entries, so "biaya dan jadwal" answers both.
  const chosen = matches.slice(0, 2);

  return {
    mode: "kb",
    answer: chosen.map((m) => m.entry.answer).join("\n\n"),
    sources: sourcesOf(chosen),
  };
}

function systemPrompt(context: string): string {
  return [
    "Kamu adalah asisten resmi TECH-C Robotic & Coding, lembaga kursus robotik dan coding di Kota Cilegon, Banten.",
    "Jawab dalam bahasa Indonesia yang ramah, jelas, dan ringkas (maksimal 120 kata).",
    "Gunakan HANYA informasi pada bagian KONTEKS di bawah. Jangan mengarang biaya, jadwal, alamat, atau janji apa pun.",
    `Jika konteks tidak memuat jawabannya, katakan bahwa kamu belum punya informasi itu dan arahkan menghubungi WhatsApp ${TECHC.phone}.`,
    "Jangan menyebut dirimu sebagai model bahasa atau menyebut nama perusahaan penyedia AI.",
    context ? `\nKONTEKS:\n${context}` : "",
  ]
    .filter(Boolean)
    .join("\n");
}

async function callModel(
  question: string,
  history: ChatTurn[],
  context: string
): Promise<string | null> {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), env.AI_TIMEOUT_MS);

  try {
    const response = await fetch(`${env.AI_BASE_URL.replace(/\/$/, "")}/chat/completions`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${env.AI_API_KEY}`,
      },
      body: JSON.stringify({
        model: env.AI_MODEL,
        temperature: 0.3,
        max_tokens: 400,
        messages: [
          { role: "system", content: systemPrompt(context) },
          ...history.slice(-MAX_HISTORY_TURNS).map((t) => ({ role: t.role, content: t.content })),
          { role: "user", content: question },
        ],
      }),
      signal: controller.signal,
      cache: "no-store",
    });

    if (!response.ok) return null;

    const payload: unknown = await response.json();
    return extractContent(payload);
  } catch {
    // Network error, timeout, malformed payload — fall back to the knowledge base.
    return null;
  } finally {
    clearTimeout(timeout);
  }
}

/** Pull `choices[0].message.content` out of an untrusted completion payload. */
function extractContent(payload: unknown): string | null {
  if (!payload || typeof payload !== "object" || !("choices" in payload)) return null;
  const choices = payload.choices;
  if (!Array.isArray(choices) || choices.length === 0) return null;

  const first: unknown = choices[0];
  if (!first || typeof first !== "object" || !("message" in first)) return null;
  const message = first.message;
  if (!message || typeof message !== "object" || !("content" in message)) return null;

  const content = message.content;
  return typeof content === "string" && content.trim().length > 0 ? content.trim() : null;
}

export async function answerQuestion(
  question: string,
  history: ChatTurn[] = []
): Promise<ChatReply> {
  const clean = question.trim().slice(0, MAX_QUESTION_CHARS);
  const entries = await loadRankableEntries();
  const matches = rankEntries(entries, clean);

  if (env.AI_API_KEY) {
    // Ground the model on the best-matching entries, plus any entry sharing a
    // salient term (so "berapa biaya private class" still sees both topics).
    const terms = salientTerms(clean);
    const extras = entries.filter(
      (e) =>
        !matches.some((m) => m.entry.id === e.id) &&
        terms.some((t) => e.keywords.some((k) => k.includes(t) || t.includes(k)))
    );

    const context = [...matches.map((m) => m.entry), ...extras.slice(0, 3)]
      .map((e) => `- ${e.topic}: ${e.answer}`)
      .join("\n");

    const answer = await callModel(clean, history, context);
    if (answer) {
      return { mode: "ai", answer, sources: sourcesOf(matches.slice(0, 2)) };
    }
    // Model unavailable — degrade to the offline answer rather than an error.
  }

  // A gap is worth recording only when nothing matched: that is the signal an
  // administrator turns into a new entry.
  if (matches.length === 0) await recordUnanswered(clean);

  return offlineReply(matches);
}

/** Whether a real model is wired up, so the UI can label the provenance. */
export function aiEnabled(): boolean {
  return Boolean(env.AI_API_KEY);
}
