using Portfolio.Application.Services.NWSWeatherService;
using Portfolio.Domain.Features.TemperatureDay;
using System.Text.Json;

namespace Portfolio.WebUI.Server.Components.Pages.Crochet_Pages
{
    public partial class TemperatureDataImporter
    {
        private readonly NWSWeatherService _weatherService;
        private readonly string _storagePath = "Data/temperature_data_2024.json"; // changeable if needed

        public bool IsImporting = true;

        public TemperatureDataImporter(NWSWeatherService weatherService)
        {
            _weatherService = weatherService;
        }

        public async Task<List<TemperatureDay>> ImportAndSaveYearAsync(int year, double latitude, double longitude)
        {
            var days = new List<TemperatureDay>();

            var stationId = await _weatherService.GetNearestStationAsync(latitude, longitude);
            if (stationId == null)
            {
                throw new Exception("Failed to find nearest station.");
            }

            var startDate = new DateTime(year, 1, 1);
            var endDate = new DateTime(year, 12, 31);

            for (var date = startDate; date <= endDate; date = date.AddDays(1))
            {
                var avgTemp = await _weatherService.GetDailyAverageTempAsync(stationId, date);
                if (avgTemp.HasValue)
                {
                    days.Add(new TemperatureDay { Date = date, AvgTemp = avgTemp.Value });
                }

                await Task.Delay(600); // Respectful API use
            }

            await SaveToFileAsync(days);

            return days;
        }

        private async Task SaveToFileAsync(List<TemperatureDay> days)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(_storagePath)!);

            var json = JsonSerializer.Serialize(days, new JsonSerializerOptions { WriteIndented = true });
            await File.WriteAllTextAsync(_storagePath, json);

            Console.WriteLine($"✅ Saved {days.Count} days to {_storagePath}");
        }

        public async Task<List<TemperatureDay>> LoadSavedDataAsync()
        {
            if (!File.Exists(_storagePath))
                throw new FileNotFoundException($"No saved temperature data found at {_storagePath}");

            var json = await File.ReadAllTextAsync(_storagePath);
            var days = JsonSerializer.Deserialize<List<TemperatureDay>>(json);

            return days ?? new List<TemperatureDay>();
        }
    }
}