using System.Text.Json; using MarketAlly.GitCommitEditor.Models; namespace MarketAlly.GitCommitEditor.Services; public sealed class FileStateRepository : IStateRepository { private readonly string _filePath; private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true }; public FileStateRepository(string filePath) { _filePath = filePath ?? throw new ArgumentNullException(nameof(filePath)); } public async Task LoadAsync(CancellationToken ct = default) { if (!File.Exists(_filePath)) return new ImproverState(); try { var json = await File.ReadAllTextAsync(_filePath, ct); return JsonSerializer.Deserialize(json) ?? new ImproverState(); } catch (JsonException) { return new ImproverState(); } catch (IOException) { return new ImproverState(); } } public async Task SaveAsync(ImproverState state, CancellationToken ct = default) { // Ensure directory exists var directory = Path.GetDirectoryName(_filePath); if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) { Directory.CreateDirectory(directory); } state.LastUpdated = DateTimeOffset.UtcNow; var json = JsonSerializer.Serialize(state, JsonOptions); await File.WriteAllTextAsync(_filePath, json, ct); } }