/** * Conversation selection when an NPC has multiple conversations. * * Each conversation may declare an entry gate (a flag condition evaluated * against the reading player) and a priority. The offer order is priority * descending, oldest first; the first conversation whose gate passes wins. * An empty gate key always passes, which makes ungated conversations the * natural fallback. Pure module: the caller injects the condition evaluator * so this stays testable and client-safe. */ import type { DialogueFlagCondition } from "./dialogue"; /** * The stored entry gate shape on an npc-dialogues document. Entry gates stay * flat leaves by design (the DB column shape predates condition groups and * gating a whole conversation with one flag is the intended use). */ export interface DialogueEntryGate { key?: string | null; op?: DialogueFlagCondition["op"] | null; amount?: number | null; } /** Minimal candidate shape the selector reads from a conversation doc. */ export interface GateCandidate { id: number; priority?: number | null; entryGate?: DialogueEntryGate | null; } /** Turns a stored gate into a runtime condition; null when ungated. */ export function gateCondition( gate: DialogueEntryGate | null | undefined, ): DialogueFlagCondition | null { const key = gate?.key?.trim(); if (!key || !gate) return null; return { kind: "flag", key, op: gate.op ?? "is_true", amount: gate.amount ?? 0 }; } /** * Picks the conversation to offer: highest priority first (ties break by * oldest id), gated conversations skipped unless `evaluate` passes their * condition. Returns null when every candidate is gated shut. */ export async function selectDialogueForUser( docs: readonly T[], evaluate: (condition: DialogueFlagCondition) => Promise, ): Promise { const ordered = [...docs].sort( (a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id - b.id, ); for (const doc of ordered) { const condition = gateCondition(doc.entryGate); if (!condition) return doc; if (await evaluate(condition)) return doc; } return null; }