using Atomx.Common.Models;
using System.Text.Json;

namespace Atomx.Admin.Services
{
    public interface ILocalizationFileService
    {
        Task<Dictionary<string, string>> GetTranslationsAsync(string culture);
        Task<bool> SaveTranslationsAsync(string version, string culture, Dictionary<string, string> translations);
        Task<bool> FileExistsAsync(string culture);
    }

    public class LocalizationFileService : ILocalizationFileService
    {
        private readonly IWebHostEnvironment _environment;
        private readonly ILogger<LocalizationFileService> _logger;
        private readonly string _resourcesPath;

        public LocalizationFileService(
            IWebHostEnvironment environment,
            ILogger<LocalizationFileService> logger)
        {
            _environment = environment;
            _logger = logger;
            _resourcesPath = Path.Combine(_environment.ContentRootPath, "Resources");

            EnsureResourcesDirectoryExists();
        }

        /// <summary>
        /// 读取指定文化语言的译文
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public async Task<Dictionary<string, string>> GetTranslationsAsync(string culture)
        {
            var filePath = GetFilePath(culture);

            if (!File.Exists(filePath))
            {
                _logger.LogWarning("Localization file not found for culture: {Culture}", culture);
                return new Dictionary<string, string>();
            }

            try
            {
                var json = await File.ReadAllTextAsync(filePath);
                var fileData = JsonSerializer.Deserialize<LocalizationFile>(json, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });

                return fileData?.Translations ?? new Dictionary<string, string>();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error reading localization file for culture: {Culture}", culture);
                return new Dictionary<string, string>();
            }
        }

        /// <summary>
        /// 保存本地化译文
        /// </summary>
        /// <param name="version"></param>
        /// <param name="culture"></param>
        /// <param name="translations"></param>
        /// <returns></returns>
        public async Task<bool> SaveTranslationsAsync(string version, string culture, Dictionary<string, string> translations)
        {
            try
            {
                var fileData = new LocalizationFile
                {
                    ResourceVersion = culture,
                    Translations = translations
                };

                var options = new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    WriteIndented = true
                };

                var json = JsonSerializer.Serialize(fileData, options);
                var filePath = GetFilePath(culture);

                await File.WriteAllTextAsync(filePath, json);

                _logger.LogInformation("Saved localization file for culture: {Culture} with {Count} translations",
                    culture, translations.Count);

                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error saving localization file for culture: {Culture}", culture);
                return false;
            }
        }

        /// <summary>
        /// 判断文化语言文件是否存在
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public Task<bool> FileExistsAsync(string culture)
        {
            var filePath = GetFilePath(culture);
            return Task.FromResult(File.Exists(filePath));
        }

        /// <summary>
        /// 获取文件最后修改时间
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public DateTime GetFileLastModified(string culture)
        {
            var filePath = GetFilePath(culture);
            return File.Exists(filePath) ? File.GetLastWriteTimeUtc(filePath) : DateTime.MinValue;
        }

        /// <summary>
        /// 获取文件路径
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        private string GetFilePath(string culture)
        {
            var fileName = $"{culture}.json";
            return Path.Combine(_resourcesPath, fileName);
        }

        /// <summary>
        /// 判断存放资源文件的文件夹是否存在，不存在则创建
        /// </summary>
        private void EnsureResourcesDirectoryExists()
        {
            if (!Directory.Exists(_resourcesPath))
            {
                Directory.CreateDirectory(_resourcesPath);
                _logger.LogInformation("Created Resources directory: {Path}", _resourcesPath);
            }
        }
    }
}
