import * as fs from 'fs';
import * as path from 'path';

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}

export function readGeminiSettings(settingsPath: string): Record<string, unknown> {
  if (!fs.existsSync(settingsPath)) {
    return {};
  }

  const raw = fs.readFileSync(settingsPath, 'utf-8');
  const parsed = JSON.parse(raw);
  if (!isRecord(parsed)) {
    throw new Error(`Gemini settings must be a JSON object: ${settingsPath}`);
  }
  return parsed;
}

export function writeGeminiSettings(settingsPath: string, settings: Record<string, unknown>): void {
  fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
  fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n', 'utf-8');
}

export function updateGeminiSettings(
  settingsPath: string,
  mutate: (settings: Record<string, unknown>) => void
): Record<string, unknown> {
  const settings = readGeminiSettings(settingsPath);
  mutate(settings);
  writeGeminiSettings(settingsPath, settings);
  return settings;
}

export function setGeminiAutoUpdateDisabled(settings: Record<string, unknown>): void {
  const general = isRecord(settings.general) ? settings.general : {};
  settings.general = {
    ...general,
    enableAutoUpdate: false,
  };
}
