using JsonRpcEndpointSample.Mcp;
using JsonRpcEndpointSample.Rpc;
using JsonRpcEndpointSample.Rpc.Abstractions;
using JsonRpcEndpointSample.Rpc.Discovery;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddScoped<IJsonRpcDispatcher, JsonRpcDispatcher>();
builder.Services.AddScoped<IMcpDispatcher, McpDispatcher>();
builder.Services.AddMcpTools(builder.Configuration);

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}


app.MapPost("/mcp", async (JsonRpcRequest request, IMcpDispatcher dispatcher) =>
{
    JsonRpcResponse response = await dispatcher.DispatchAsync(request);
    return Results.Ok(response);
})
.WithName("McpEndpoint")
.WithSummary("Executes an MCP-style JSON-RPC request.")
.WithDescription("Supports initialize, tools/list, and tools/call over one endpoint. This is a small learning-oriented MCP-style adapter over the same registered RPC handlers.");

app.MapPost("/rpc", async (JsonRpcRequest request, IJsonRpcDispatcher dispatcher) =>
{
    JsonRpcResponse response = await dispatcher.DispatchAsync(request);
    return Results.Ok(response);
})
.WithName("JsonRpcEndpoint")
.WithSummary("Executes a JSON-RPC 2.0 request.")
.WithDescription("Send all JSON-RPC calls to this single endpoint. The method field selects the registered RPC handler.");

app.MapGet("/rpc/methods", (IEnumerable<RpcMethodDescriptor> methodDescriptors) =>
{
    List<RpcMethodDescriptor> methods = methodDescriptors
        .OrderBy(methodDescriptor => methodDescriptor.Method)
        .ToList();

    return Results.Ok(methods);
})
.WithName("JsonRpcMethodCatalog")
.WithSummary("Lists registered JSON-RPC methods.")
.WithDescription("Returns the discoverable method catalog for methods handled behind the single /rpc endpoint.");

app.MapGet("/rpc/tools", (IEnumerable<RpcToolDescriptor> toolDescriptors) =>
{
    List<RpcToolDescriptor> tools = toolDescriptors
        .OrderBy(toolDescriptor => toolDescriptor.Name)
        .ToList();

    return Results.Ok(tools);
})
.WithName("JsonRpcAiToolCatalog")
.WithSummary("Lists AI-friendly JSON-RPC tools.")
.WithDescription("Returns tool names, descriptions, input schemas, output schemas, and invocation examples for AI agents and tool-aware clients.");

app.Run();
