import { env as cfEnv } from 'cloudflare:workers';
import { getFullDb, type DbEnv } from './db';
import { getAllSettings, SETTINGS_KEYS } from './settings';
import { parseActiveSelection, DEFAULT_SELECTION } from './theme';
import type { ActiveSelection } from '@platform-modules/ui-tokens/theme-engine';

/**
 * Read the stored `theme` setting and resolve to an ActiveSelection. ALWAYS resolves
 * (availability Hard floor) — a settings read failure falls back to DEFAULT_SELECTION.
 * Used by the post page to pick its theme body before wrapping in <Base>.
 */
export async function loadAppearanceSelection(env: typeof cfEnv): Promise<ActiveSelection> {
  try {
    const settings = await getAllSettings(getFullDb(env).db);
    return parseActiveSelection(settings[SETTINGS_KEYS.theme]);
  } catch {
    return DEFAULT_SELECTION;
  }
}
