/// CLI host adapter for persisting renderer settings to a local file.
library;

import 'dart:io';

import 'package:wolf_3d_dart/wolf_3d_engine.dart';

/// Persists [WolfRendererSettings] as JSON to a local file.
///
/// The default path is `~/.wolf3d_cli_settings.json`.
/// An alternative [filePath] can be supplied at construction time.
class CliRendererSettingsPersistence extends RendererSettingsPersistence
    with JsonRendererSettingsPersistence {
  CliRendererSettingsPersistence({String? filePath})
    : _filePath =
          filePath ??
          '${Platform.environment['HOME'] ?? '.'}/.wolf3d_cli_settings.json';

  final String _filePath;

  @override
  Future<String?> readRaw() async {
    try {
      final File f = File(_filePath);
      if (!f.existsSync()) {
        return null;
      }
      return await f.readAsString();
    } catch (_) {
      return null;
    }
  }

  @override
  Future<void> writeRaw(String json) async {
    try {
      await File(_filePath).writeAsString(json, flush: true);
    } catch (_) {
      // Best-effort; never crash the loop on a write failure.
    }
  }
}
