import { apiV2Data, apiV2Raw } from "@/lib/apiV2"; import type { V2Result } from "@/lib/apiV2"; /** * AI helpers (2.0). The site calls AI through the Cross Events Hub, which keeps a monthly * allowance per licence, shown here as tokens and a percentage (2.2.0). One status per page load is shared by every AI button * (`useAiStatus`), and every helper call refreshes it — so the buttons disable straight after the * call that used up the allowance. */ export type AiStatus = V2Result<"/ai/status", "get">["data"]; export type AiHelper = keyof AiStatus["helpers"]; const OFF: AiStatus = { enabled: false, capReached: false, available: true, usedPercent: 0, renewsOn: null, usedInputTokens: null, usedOutputTokens: null, capInputTokens: null, capOutputTokens: null, helpers: { draft_event: false, summarise_report: false, draft_message: false, summarise_feedback: false, improve_text: false }, }; let current: AiStatus | null = null; let loading: Promise | null = null; const listeners = new Set<(s: AiStatus) => void>(); function publish(s: AiStatus) { current = s; listeners.forEach(l => l(s)); } /** The status, fetched once per page load (staff never see AI, so they never ask). */ export function loadAiStatus(authToken: string, { fresh = false } = {}): Promise { if (current && !fresh) return Promise.resolve(current); if (!loading || fresh) { loading = (apiV2Data("get", "/ai/status", { authToken }) as Promise) .then(s => { publish(s); return s; }) .catch(() => { publish(OFF); return OFF; }) .finally(() => { loading = null; }); } return loading; } export function subscribeAiStatus(fn: (s: AiStatus) => void): () => void { listeners.add(fn); return () => { listeners.delete(fn); }; } export function currentAiStatus(): AiStatus | null { return current; } /** "800", "45K", "1.2M": token counts for people (the allowance is shown in tokens, never rand). */ export function tokenText(n: number): string { if (n >= 1e6) return `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1).replace(/\.0$/, "")}M`; if (n >= 1e3) return `${Math.round(n / 1e3)}K`; return String(n); } /** "1 December" from "2026-12-01". */ export function renewsText(renewsOn: string | null): string { if (!renewsOn) return "next month"; return new Date(`${renewsOn}T12:00:00Z`).toLocaleDateString("en-ZA", { day: "numeric", month: "long" }); } /** What the button's tooltip says when it can't be used. */ export function disabledReason(s: AiStatus, helper: AiHelper): string | null { if (s.capReached) return `This month's AI allowance is used up — it renews on ${renewsText(s.renewsOn)}.`; if (!s.available) return "AI is unavailable right now. Try again in a few minutes."; if (!s.helpers[helper]) return "This AI helper is switched off in Site settings → AI."; return null; } /** * Run a helper (`POST /api/v2/ai/`). Resolves to its answer; throws the API error (with * a message written for people). Either way the shared status is refreshed. */ export async function runAi(helper: AiHelper, body: object, authToken: string): Promise { try { const res = await apiV2Raw<{ output: T; status: AiStatus }>("post", `/ai/${helper.replace(/_/g, "-")}`, { authToken, body }); publish(res.status); return res.output; } catch (e) { loadAiStatus(authToken, { fresh: true }).catch(() => {}); throw e; } }