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<string, int> _counts = new Dictionary<string, int>(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<T> SortByUsage<T>(IEnumerable<T> items, Func<T, string?> 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<string, int> dictionary = JsonSerializer.Deserialize<Dictionary<string, int>>(json);
					if (dictionary != null)
					{
						_counts = new Dictionary<string, int>(dictionary, StringComparer.OrdinalIgnoreCase);
					}
				}
			}
			catch (Exception ex)
			{
				LogService.Warn("usage.json 로드 실패: " + ex.Message);
			}
			_loaded = true;
		}
	}

	private static async Task SaveAsync()
	{
		try
		{
			Dictionary<string, int> snapshot;
			lock (_lock)
			{
				snapshot = new Dictionary<string, int>(_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);
		}
	}
}
