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(
    ILogger<ResourcesListMethodHandler> logger,
    IMcpResourceRegistry resourceRegistry)
    : IMcpMethodHandler
{
    public string MethodName => "resources/list";

    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);
    }
}
