import "server-only";
import { prisma } from "@/lib/db";
import { BUNDLED_ENTRIES, slugifyTopic, type RankableEntry } from "@/lib/ai/knowledge";

/**
 * Assistant knowledge access.
 *
 * The knowledge base is admin-managed: rows live in `knowledge_entries` and are
 * matched by the same ranker that ships with the bundled defaults. When the
 * table is empty the bundled entries take over, so a fresh install answers
 * questions before anyone has opened the admin console.
 */

export interface KnowledgeRow {
  id: string;
  topic: string;
  keywords: string[];
  answer: string;
  priority: number;
  published: boolean;
  seededId: string | null;
  updatedAt: Date;
}

export interface UnansweredRow {
  id: string;
  question: string;
  hits: number;
  resolvedAt: Date | null;
  lastAskedAt: Date;
}

/** `keywords` is a JSON column, so its runtime shape is not guaranteed. */
function toStringArray(value: unknown): string[] {
  if (!Array.isArray(value)) return [];
  return value.filter((item): item is string => typeof item === "string" && item.trim().length > 0);
}

/** Load the published knowledge, falling back to the bundled defaults. */
export async function loadRankableEntries(): Promise<RankableEntry[]> {
  try {
    const rows = await prisma.knowledgeEntry.findMany({
      where: { published: true },
      select: {
        id: true,
        topic: true,
        keywords: true,
        answer: true,
        priority: true,
        seededId: true,
      },
      orderBy: [{ priority: "desc" }, { createdAt: "asc" }],
    });

    const entries: RankableEntry[] = rows.map((row) => ({
      id: row.id,
      // A seeded row keeps its bundled slug so the intent rules still fire;
      // an admin-authored row gets one derived from its topic.
      slug: row.seededId ?? slugifyTopic(row.topic),
      topic: row.topic,
      keywords: toStringArray(row.keywords),
      answer: row.answer,
      priority: row.priority,
    }));

    // A table with rows but no usable keywords would answer nothing; prefer the
    // bundled set until an administrator has saved something matchable.
    return entries.some((entry) => entry.keywords.length > 0) ? entries : BUNDLED_ENTRIES;
  } catch {
    // Database unreachable — the public assistant must still respond.
    return BUNDLED_ENTRIES;
  }
}

export async function listKnowledgeEntries(): Promise<KnowledgeRow[]> {
  const rows = await prisma.knowledgeEntry.findMany({
    select: {
      id: true,
      topic: true,
      keywords: true,
      answer: true,
      priority: true,
      published: true,
      seededId: true,
      updatedAt: true,
    },
    orderBy: [{ priority: "desc" }, { topic: "asc" }],
  });

  return rows.map((row) => ({
    id: row.id,
    topic: row.topic,
    keywords: toStringArray(row.keywords),
    answer: row.answer,
    priority: row.priority,
    published: row.published,
    seededId: row.seededId,
    updatedAt: row.updatedAt,
  }));
}

export async function getKnowledgeEntry(id: string): Promise<KnowledgeRow | null> {
  const row = await prisma.knowledgeEntry.findUnique({
    where: { id },
    select: {
      id: true,
      topic: true,
      keywords: true,
      answer: true,
      priority: true,
      published: true,
      seededId: true,
      updatedAt: true,
    },
  });
  if (!row) return null;

  return {
    id: row.id,
    topic: row.topic,
    keywords: toStringArray(row.keywords),
    answer: row.answer,
    priority: row.priority,
    published: row.published,
    seededId: row.seededId,
    updatedAt: row.updatedAt,
  };
}

export async function countKnowledgeEntries(): Promise<{ total: number; published: number }> {
  const [total, published] = await Promise.all([
    prisma.knowledgeEntry.count(),
    prisma.knowledgeEntry.count({ where: { published: true } }),
  ]);
  return { total, published };
}

/** Questions the assistant could not answer, most-asked first. */
export async function listUnansweredQuestions(includeResolved = false): Promise<UnansweredRow[]> {
  const rows = await prisma.unansweredQuestion.findMany({
    where: includeResolved ? {} : { resolvedAt: null },
    select: { id: true, question: true, hits: true, resolvedAt: true, lastAskedAt: true },
    orderBy: [{ hits: "desc" }, { lastAskedAt: "desc" }],
    take: 50,
  });

  return rows.map((row) => ({
    id: row.id,
    question: row.question,
    hits: row.hits,
    resolvedAt: row.resolvedAt,
    lastAskedAt: row.lastAskedAt,
  }));
}

export async function countUnansweredQuestions(): Promise<number> {
  return prisma.unansweredQuestion.count({ where: { resolvedAt: null } });
}

/**
 * Normalise a question so the same gap asked twice increments one row instead
 * of filling the console with near-duplicates.
 */
function fingerprint(question: string): string {
  return question
    .toLowerCase()
    .replace(/[^\p{L}\p{N}\s]/gu, " ")
    .replace(/\s+/g, " ")
    .trim()
    .slice(0, 200);
}

/** Rows kept before the oldest unresolved questions are pruned. */
const UNANSWERED_LIMIT = 500;

/**
 * Record a question that produced no answer.
 *
 * Best-effort: this runs on a public endpoint, so a logging failure must never
 * surface to the visitor or delay the reply. The table is capped because anyone
 * can reach that endpoint — duplicates collapse via `fingerprint`, and the
 * pruning below keeps a determined visitor from growing it without bound.
 */
export async function recordUnanswered(question: string): Promise<void> {
  const key = fingerprint(question);
  if (key.length < 4) return;

  try {
    await prisma.unansweredQuestion.upsert({
      where: { fingerprint: key },
      create: { question: question.slice(0, 300), fingerprint: key },
      update: { hits: { increment: 1 }, lastAskedAt: new Date() },
    });

    // Sampled rather than run per request: a count on every ask would cost more
    // than the pruning saves, and the table tolerates overshooting the cap.
    if (Math.random() < 0.05) {
      const total = await prisma.unansweredQuestion.count();
      if (total > UNANSWERED_LIMIT) {
        const stale = await prisma.unansweredQuestion.findMany({
          where: { resolvedAt: null },
          select: { id: true },
          orderBy: [{ hits: "asc" }, { lastAskedAt: "asc" }],
          take: total - UNANSWERED_LIMIT,
        });
        if (stale.length > 0) {
          await prisma.unansweredQuestion.deleteMany({
            where: { id: { in: stale.map((row) => row.id) } },
          });
        }
      }
    }
  } catch {
    // Ignored by design.
  }
}
