using System.Text.Json;
using ColaFlow.Modules.Mcp.Contracts.Mcp;
using Microsoft.Extensions.Logging;

namespace ColaFlow.Modules.Mcp.Application.Handlers;

/// <summary>
/// Handler for the 'initialize' MCP method
/// </summary>
public class InitializeMethodHandler : IMcpMethodHandler
{
    private readonly ILogger<InitializeMethodHandler> _logger;

    public string MethodName => "initialize";

    public InitializeMethodHandler(ILogger<InitializeMethodHandler> logger)
    {
        _logger = logger;
    }

    public Task<object?> HandleAsync(object? @params, CancellationToken cancellationToken)
    {
        try
        {
            // Parse initialize request
            McpInitializeRequest? initRequest = null;
            if (@params != null)
            {
                var json = JsonSerializer.Serialize(@params);
                initRequest = JsonSerializer.Deserialize<McpInitializeRequest>(json);
            }

            _logger.LogInformation(
                "MCP Initialize handshake received. Client: {ClientName} {ClientVersion}, Protocol: {ProtocolVersion}",
                initRequest?.ClientInfo?.Name ?? "Unknown",
                initRequest?.ClientInfo?.Version ?? "Unknown",
                initRequest?.ProtocolVersion ?? "Unknown");

            // Validate protocol version
            if (initRequest?.ProtocolVersion != "1.0")
            {
                _logger.LogWarning("Unsupported protocol version: {ProtocolVersion}", initRequest?.ProtocolVersion);
            }

            // Create initialize response
            var response = new McpInitializeResponse
            {
                ProtocolVersion = "1.0",
                ServerInfo = new McpServerInfo
                {
                    Name = "ColaFlow MCP Server",
                    Version = "1.0.0"
                },
                Capabilities = McpServerCapabilities.CreateDefault()
            };

            _logger.LogInformation("MCP Initialize handshake completed successfully");

            return Task.FromResult<object?>(response);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error handling initialize request");
            throw;
        }
    }
}
