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

namespace ColaFlow.Modules.Mcp.Application.Handlers;

/// <summary>
/// Handler for the 'resources/list' MCP method
/// Returns categorized list of all available resources with full metadata
/// </summary>
public class ResourcesListMethodHandler : IMcpMethodHandler
{
    private readonly ILogger<ResourcesListMethodHandler> _logger;
    private readonly IMcpResourceRegistry _resourceRegistry;

    public string MethodName => "resources/list";

    public ResourcesListMethodHandler(
        ILogger<ResourcesListMethodHandler> logger,
        IMcpResourceRegistry resourceRegistry)
    {
        _logger = logger;
        _resourceRegistry = resourceRegistry;
    }

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

        // Get all registered resource descriptors with full metadata
        var descriptors = _resourceRegistry.GetResourceDescriptors();
        var categories = _resourceRegistry.GetCategories();

        _logger.LogInformation("Returning {Count} MCP resources in {CategoryCount} categories",
            descriptors.Count, categories.Count);

        // Group by category for better organization
        var resourcesByCategory = descriptors
            .GroupBy(d => d.Category)
            .OrderBy(g => g.Key)
            .ToDictionary(
                g => g.Key,
                g => g.Select(d => new
                {
                    uri = d.Uri,
                    name = d.Name,
                    description = d.Description,
                    mimeType = d.MimeType,
                    version = d.Version,
                    parameters = d.Parameters,
                    examples = d.Examples,
                    tags = d.Tags,
                    isEnabled = d.IsEnabled
                }).ToArray()
            );

        var response = new
        {
            resources = descriptors.Select(d => new
            {
                uri = d.Uri,
                name = d.Name,
                description = d.Description,
                mimeType = d.MimeType,
                category = d.Category,
                version = d.Version,
                parameters = d.Parameters,
                examples = d.Examples,
                tags = d.Tags,
                isEnabled = d.IsEnabled
            }).ToArray(),
            categories = categories.ToArray(),
            resourcesByCategory = resourcesByCategory,
            totalCount = descriptors.Count,
            categoryCount = categories.Count
        };

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