import { z } from 'zod'; import type { DB } from './db.ts'; import { parseJson } from './util.ts'; export function getSetting(db: DB, key: string, fallback: T): T { const row = db.get<{ value: string }>('SELECT value FROM settings WHERE key = ?', key); return row ? parseJson(row.value, fallback) : fallback; } export function setSetting(db: DB, key: string, value: unknown): void { db.run('INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value', key, JSON.stringify(value)); } export function deleteSetting(db: DB, key: string): void { db.run('DELETE FROM settings WHERE key = ?', key); } export const appSettingsSchema = z.object({ timezone: z.string().min(1).max(64), /** New flashcards introduced per day across all decks. */ newCardsPerDay: z.number().int().min(0).max(500), /** Target recall probability used by FSRS (0.7 - 0.97). */ desiredRetention: z.number().min(0.7).max(0.97), sataScoring: z.enum(['partial', 'strict']), /** Cards + questions per day that count as "studied" for the streak. */ dailyGoal: z.number().int().min(1).max(1000), }); export type AppSettings = z.infer; export function getAppSettings(db: DB, defaultTimezone: string): AppSettings { const stored = getSetting>(db, 'app', {}); const merged = { timezone: defaultTimezone, newCardsPerDay: 20, desiredRetention: 0.9, sataScoring: 'partial' as const, dailyGoal: 20, ...stored, }; const parsed = appSettingsSchema.safeParse(merged); return parsed.success ? parsed.data : { timezone: defaultTimezone, newCardsPerDay: 20, desiredRetention: 0.9, sataScoring: 'partial', dailyGoal: 20 }; }