import { copyFileSync, existsSync, mkdirSync, renameSync, writeFileSync } from 'fs';
import { dirname } from 'path';
import { stringify } from 'yaml';
import type { Config } from './schema.js';

/**
 * Persist config atomically:
 * 1) Backup existing file to <path>.bak
 * 2) Write new YAML to temp file
 * 3) Rename temp file into place
 */
export function persistConfig(configPath: string, config: Config): void {
  const dir = dirname(configPath);
  mkdirSync(dir, { recursive: true });

  const yaml = stringify(config);
  const tmpPath = `${configPath}.tmp-${process.pid}-${Date.now()}`;
  const backupPath = `${configPath}.bak`;

  if (existsSync(configPath)) {
    copyFileSync(configPath, backupPath);
  }

  writeFileSync(tmpPath, yaml, 'utf-8');
  renameSync(tmpPath, configPath);
}
