import { readFileSync, writeFileSync, mkdirSync } from 'fs';
import { dirname, resolve } from 'path';

export interface Preferences {
  modelTier?: string;
  backendMode?: BackendModePreference;
}

export type BackendModePreference = 'config_default' | 'force_native' | 'force_pi_embedded';

function isBackendModePreference(value: unknown): value is BackendModePreference {
  return value === 'config_default' || value === 'force_native' || value === 'force_pi_embedded';
}

export function loadPreferences(dataDir: string): Preferences {
  const filePath = resolve(dataDir, 'preferences.json');
  try {
    const raw = readFileSync(filePath, 'utf-8');
    const parsed = JSON.parse(raw) as Record<string, unknown>;
    const prefs: Preferences = {};
    if (typeof parsed.modelTier === 'string') {
      prefs.modelTier = parsed.modelTier;
    }
    if (isBackendModePreference(parsed.backendMode)) {
      prefs.backendMode = parsed.backendMode;
    }
    return prefs;
  } catch {
    return {};
  }
}

export function savePreference(dataDir: string, key: string, value: unknown): void {
  const filePath = resolve(dataDir, 'preferences.json');
  let prefs: Record<string, unknown> = {};
  try {
    prefs = JSON.parse(readFileSync(filePath, 'utf-8'));
  } catch {
    // start fresh
  }
  prefs[key] = value;
  mkdirSync(dirname(filePath), { recursive: true });
  writeFileSync(filePath, JSON.stringify(prefs, null, 2) + '\n');
}
