using ColaFlow.Modules.Mcp.Application.Services;
using ColaFlow.Modules.Mcp.Contracts.Resources;
using Microsoft.Extensions.Logging;

namespace ColaFlow.Modules.Mcp.Application.Handlers;

/// <summary>
/// Handler for 'resources/health' method
/// Checks availability and health of all registered resources
/// </summary>
public class ResourceHealthCheckHandler(
    ILogger<ResourceHealthCheckHandler> logger,
    IMcpResourceRegistry resourceRegistry)
    : IMcpMethodHandler
{
    public string MethodName => "resources/health";

    public async Task<object?> HandleAsync(object? @params, CancellationToken cancellationToken)
    {
        logger.LogDebug("Handling resources/health request");

        var resources = resourceRegistry.GetAllResources();
        var healthResults = new List<object>();
        var totalResources = resources.Count;
        var healthyResources = 0;
        var unhealthyResources = 0;

        foreach (var resource in resources)
        {
            try
            {
                // Try to get descriptor - if this fails, resource is unhealthy
                var descriptor = resource.GetDescriptor();

                // Basic validation
                var isHealthy = !string.IsNullOrWhiteSpace(descriptor.Uri)
                    && !string.IsNullOrWhiteSpace(descriptor.Name)
                    && descriptor.IsEnabled;

                if (isHealthy)
                {
                    healthyResources++;
                }
                else
                {
                    unhealthyResources++;
                }

                healthResults.Add(new
                {
                    uri = descriptor.Uri,
                    name = descriptor.Name,
                    category = descriptor.Category,
                    status = isHealthy ? "healthy" : "unhealthy",
                    isEnabled = descriptor.IsEnabled,
                    version = descriptor.Version
                });
            }
            catch (Exception ex)
            {
                unhealthyResources++;
                logger.LogError(ex, "Health check failed for resource {ResourceType}", resource.GetType().Name);

                healthResults.Add(new
                {
                    uri = resource.Uri,
                    name = resource.Name,
                    category = resource.Category,
                    status = "error",
                    error = ex.Message
                });
            }
        }

        var overallStatus = unhealthyResources == 0 ? "healthy" : "degraded";

        logger.LogInformation("Resource health check completed: {Healthy}/{Total} healthy",
            healthyResources, totalResources);

        var response = new
        {
            status = overallStatus,
            totalResources = totalResources,
            healthyResources = healthyResources,
            unhealthyResources = unhealthyResources,
            timestamp = DateTime.UtcNow,
            resources = healthResults
        };

        return await Task.FromResult<object?>(response);
    }
}
