using System.Text.Json;
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace Managing.Api.HealthChecks
{
    public class GmxConnectivityHealthCheck : IHealthCheck
    {
        private readonly HttpClient _httpClient;
        private readonly string _gmxCandlesEndpoint = "https://arbitrum-api.gmxinfra.io/prices/candles?tokenSymbol=ETH&period=1m&limit=2";

        public GmxConnectivityHealthCheck(IHttpClientFactory httpClientFactory)
        {
            _httpClient = httpClientFactory.CreateClient("GmxHealthCheck");
        }

        public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                var response = await _httpClient.GetAsync(_gmxCandlesEndpoint, cancellationToken);
                
                if (!response.IsSuccessStatusCode)
                {
                    return HealthCheckResult.Degraded(
                        $"GMX API returned non-success status code: {response.StatusCode}",
                        data: new Dictionary<string, object>
                        {
                            ["StatusCode"] = (int)response.StatusCode,
                            ["Endpoint"] = _gmxCandlesEndpoint
                        });
                }

                var content = await response.Content.ReadAsStringAsync(cancellationToken);
                
                // Parse the JSON to verify it's valid and has the expected structure
                using (JsonDocument document = JsonDocument.Parse(content))
                {
                    var root = document.RootElement;
                    
                    // Check if the response has the expected structure
                    if (!root.TryGetProperty("candles", out var candlesElement) || 
                        candlesElement.ValueKind != JsonValueKind.Array ||
                        candlesElement.GetArrayLength() == 0)
                    {
                        return HealthCheckResult.Degraded(
                            "GMX API returned an invalid or empty response",
                            data: new Dictionary<string, object>
                            {
                                ["Endpoint"] = _gmxCandlesEndpoint,
                                ["Response"] = content
                            });
                    }

                    // Get the first candle timestamp to verify freshness
                    var firstCandle = candlesElement[0];
                    if (firstCandle.ValueKind != JsonValueKind.Array || firstCandle.GetArrayLength() < 1)
                    {
                        return HealthCheckResult.Degraded(
                            "GMX API returned invalid candle data format",
                            data: new Dictionary<string, object>
                            {
                                ["Endpoint"] = _gmxCandlesEndpoint,
                                ["Response"] = content
                            });
                    }

                    // Extract timestamp from the first element of the candle array
                    var timestamp = firstCandle[0].GetInt64();
                    var candleTime = DateTimeOffset.FromUnixTimeSeconds(timestamp).UtcDateTime;
                    var timeDiff = DateTime.UtcNow - candleTime;

                    return HealthCheckResult.Healthy(
                        "GMX API is responding with valid candle data",
                        data: new Dictionary<string, object>
                        {
                            ["Endpoint"] = _gmxCandlesEndpoint,
                            ["LatestCandleTimestamp"] = candleTime,
                            ["TimeDifference"] = $"{timeDiff.TotalMinutes:F2} minutes",
                            ["CandleCount"] = candlesElement.GetArrayLength()
                        });
                }
            }
            catch (Exception ex)
            {
                return HealthCheckResult.Unhealthy(
                    "Failed to connect to GMX API",
                    ex,
                    data: new Dictionary<string, object>
                    {
                        ["Endpoint"] = _gmxCandlesEndpoint,
                        ["ErrorMessage"] = ex.Message,
                        ["ErrorType"] = ex.GetType().Name
                    });
            }
        }
    }
} 