using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Nexus.Api.DTOs;
using Nexus.Api.Integrations;

namespace Nexus.Api.Controllers;

[ApiController]
[Route("api/v1/chat")]
public class ChatController(IAgentRuntime runtime, ILogger<ChatController> logger) : ControllerBase
{
    [HttpPost]
    [EnableRateLimiting("agents")]
    public async Task<IResult> Chat([FromBody] ChatRequest request, CancellationToken ct)
    {
        var message = request.Message?.Trim();
        if (string.IsNullOrWhiteSpace(message) || message.Length > 8000)
            return Results.ValidationProblem(new Dictionary<string, string[]> { ["message"] = ["Message must contain between 1 and 8000 characters."] });

        var agentId = string.IsNullOrWhiteSpace(request.AgentId) ? "iris" : request.AgentId.Trim().ToLowerInvariant();
        if (agentId is not ("iris" or "main"))
            return Results.ValidationProblem(new Dictionary<string, string[]> { ["agentId"] = ["Only iris and main are supported."] });

        var conversationId = string.IsNullOrWhiteSpace(request.ConversationId)
            ? $"nexus-{Guid.NewGuid():N}"
            : request.ConversationId.Trim();
        if (conversationId.Length > 160)
            return Results.ValidationProblem(new Dictionary<string, string[]> { ["conversationId"] = ["Conversation id is too long."] });

        try
        {
            return Results.Ok(await runtime.ChatAsync(message, conversationId, agentId, ct));
        }
        catch (Exception exception)
        {
            logger.LogWarning(exception, "OpenClaw chat request failed for agent {AgentId}", agentId);
            return Results.Problem(
                title: "OpenClaw chat unavailable",
                detail: "The trusted OpenClaw chat endpoint is not enabled or reachable.",
                statusCode: StatusCodes.Status503ServiceUnavailable);
        }
    }
}
