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

namespace Nexus.Api.Controllers;

[ApiController]
[Route("api/v1/agents")]
public class AgentsController(
    IAgentService agentService,
    IAgentRuntime runtime,
    IActivityRepository activityRepo,
    IAgentConfigService agentConfigService,
    ILogger<AgentsController> logger) : ControllerBase
{
    [HttpGet]
    public async Task<IResult> GetAgents(CancellationToken ct)
    {
        var agents = await agentService.GetAgentsAsync(ct);
        return Results.Ok(agents.Select(a => new AgentListResponse(
            a.Id, a.Name, a.Role, a.Model, a.Status.ToString(), a.LastSeen, a.Workspace, a.Description)));
    }

    [HttpGet("{id}")]
    public async Task<IResult> GetAgent(string id, CancellationToken ct)
    {
        var agent = await agentService.GetAgentAsync(id, ct);
        if (agent is null) return Results.NotFound();
        return Results.Ok(new AgentDetailResponse(
            agent.Id, agent.Name, agent.Role, agent.Model, agent.Status.ToString(),
            agent.LastSeen, agent.Workspace, agent.AgentDir, agent.Description,
            agent.SubAgents, agent.IdentityName));
    }

    [HttpGet("{id}/activity")]
    public async Task<IResult> GetAgentActivity(string id, CancellationToken ct)
    {
        var items = await activityRepo.GetByAgentAsync(id, 50, ct);
        return Results.Ok(items.Select(x => new { x.Id, x.Type, x.Message, at = x.CreatedAt }));
    }

    [HttpPost("{id}/command")]
    [EnableRateLimiting("agents")]
    public async Task<IResult> SendCommand(string id, [FromBody] AgentCommandRequest 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 conversationId = $"nexus-command-{id}-{Guid.NewGuid():N}";

        try
        {
            var result = await runtime.ChatAsync(message, conversationId, id, ct);
            await activityRepo.AddAsync(new Data.ActivityEvent { Type = "agent", Message = $"Command sent to agent {id}: {message[..Math.Min(message.Length, 80)]}" }, ct);
            return Results.Ok(new AgentCommandResponse(result.Runtime, result.AgentId, result.ConversationId, result.Content));
        }
        catch (Exception exception)
        {
            logger.LogWarning(exception, "Agent command failed for {AgentId}", id);
            return Results.Problem(
                title: "Agent command failed",
                detail: $"Could not send command to agent {id}: {exception.Message}",
                statusCode: StatusCodes.Status503ServiceUnavailable);
        }
    }

    // ── Config Editor ──

    [HttpGet("{id}/config")]
    public IResult GetConfig(string id)
        => Results.Ok(agentConfigService.GetConfigFiles(id));

    [HttpGet("{id}/config/{fileName}")]
    public async Task<IResult> GetConfigFile(string id, string fileName, CancellationToken ct)
    {
        var file = await agentConfigService.GetConfigFileAsync(id, fileName, ct);
        return file is null
            ? Results.NotFound()
            : Results.Ok(new { file.FileName, file.Content, file.Size, file.ModifiedAt });
    }

    [HttpPut("{id}/config/{fileName}")]
    public async Task<IResult> SaveConfigFile(string id, string fileName, [FromBody] SaveConfigRequest request, CancellationToken ct)
    {
        if (request.Content is null)
            return Results.BadRequest(new { error = "Content is required." });

        if (request.Content.Length > 500 * 1024)
            return Results.BadRequest(new { error = "Content exceeds maximum size of 500KB." });

        try
        {
            var result = await agentConfigService.SaveConfigFileAsync(id, fileName, request.Content, ct);
            return result is null
                ? Results.BadRequest(new { error = "Invalid filename or path." })
                : Results.Ok(new { result.FileName, result.Size, result.ModifiedAt });
        }
        catch (UnauthorizedAccessException ex)
        {
            logger.LogError(ex, "Permission denied saving config file {FileName} for agent {AgentId}", fileName, id);
            return Results.Problem(
                title: "Permission denied",
                detail: $"Cannot write config file '{fileName}' for agent '{id}'. The target path may be owned by a different user.",
                statusCode: StatusCodes.Status500InternalServerError);
        }
        catch (IOException ex)
        {
            logger.LogError(ex, "I/O error saving config file {FileName} for agent {AgentId}", fileName, id);
            return Results.Problem(
                title: "File write error",
                detail: $"Failed to write config file '{fileName}' for agent '{id}': {ex.Message}",
                statusCode: StatusCodes.Status500InternalServerError);
        }
    }
}
