using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; using System.Threading.Tasks; namespace AxCopilot.Services; internal static class UsageRankingService { private static readonly string _dataFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "AxCopilot", "usage.json"); private static Dictionary _counts = new Dictionary(StringComparer.OrdinalIgnoreCase); private static bool _loaded = false; private static readonly object _lock = new object(); public static void RecordExecution(string key) { if (!string.IsNullOrWhiteSpace(key)) { EnsureLoaded(); lock (_lock) { _counts.TryGetValue(key, out var value); _counts[key] = value + 1; } SaveAsync(); } } public static int GetScore(string key) { if (string.IsNullOrWhiteSpace(key)) { return 0; } EnsureLoaded(); lock (_lock) { int value; return _counts.TryGetValue(key, out value) ? value : 0; } } public static IEnumerable SortByUsage(IEnumerable items, Func keySelector) { EnsureLoaded(); return from x in items.Select((T item, int idx) => (item: item, idx: idx, score: GetScore(keySelector(item) ?? ""))) orderby x.score descending, x.idx select x.item; } private static void EnsureLoaded() { if (_loaded) { return; } lock (_lock) { if (_loaded) { return; } try { if (File.Exists(_dataFile)) { string json = File.ReadAllText(_dataFile); Dictionary dictionary = JsonSerializer.Deserialize>(json); if (dictionary != null) { _counts = new Dictionary(dictionary, StringComparer.OrdinalIgnoreCase); } } } catch (Exception ex) { LogService.Warn("usage.json 로드 실패: " + ex.Message); } _loaded = true; } } private static async Task SaveAsync() { try { Dictionary snapshot; lock (_lock) { snapshot = new Dictionary(_counts); } Directory.CreateDirectory(Path.GetDirectoryName(_dataFile)); await File.WriteAllTextAsync(contents: JsonSerializer.Serialize(snapshot, new JsonSerializerOptions { WriteIndented = false }), path: _dataFile); } catch (Exception ex) { Exception ex2 = ex; LogService.Warn("usage.json 저장 실패: " + ex2.Message); } } }