/// Flutter host adapter for persisting renderer settings to a local file.
///
/// Uses `dart:io` for desktop targets where a writable path is available.
/// On web and other platforms that lack dart:io, persistence is silently
/// skipped so the rest of the app continues to work normally.
library;

import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:wolf_3d_dart/wolf_3d_engine.dart';

/// Persists [WolfRendererSettings] as JSON to the app's support directory.
///
/// This implementation relies on `dart:io` and is therefore only active on
/// non-web platforms.  Pass an explicit [filePath] during testing.
class FlutterRendererSettingsPersistence extends RendererSettingsPersistence
    with JsonRendererSettingsPersistence {
  FlutterRendererSettingsPersistence({String? filePath}) : _filePath = filePath;

  final String? _filePath;
  String? _resolvedPath;

  Future<String> _getFilePath() async {
    if (_resolvedPath != null) {
      return _resolvedPath!;
    }
    if (_filePath != null) {
      _resolvedPath = _filePath;
      return _resolvedPath!;
    }
    // Resolve platform app-support directory.
    final String home =
        Platform.environment['HOME'] ?? Platform.environment['APPDATA'] ?? '.';
    _resolvedPath = '$home/.wolf3d_settings.json';
    return _resolvedPath!;
  }

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

  @override
  Future<void> writeRaw(String json) async {
    if (kIsWeb) return;
    try {
      final String path = await _getFilePath();
      await File(path).writeAsString(json, flush: true);
    } catch (_) {
      // Best-effort.
    }
  }
}
