using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Nexus.Api.Integrations;

namespace Nexus.Api.Controllers;

[ApiController]
public class HealthController(IAgentRuntime runtime, HealthCheckService healthChecks) : ControllerBase
{
    [AllowAnonymous]
    [HttpGet("/health/live")]
    public IResult Live()
    {
        return Results.Ok(new { status = "Healthy", timestamp = DateTimeOffset.UtcNow });
    }

    [HttpGet("/health")]
    public async Task<IResult> Get(CancellationToken ct)
    {
        var report = await healthChecks.CheckHealthAsync(ct);

        string runtimeStatus;
        string? runtimeDetail;
        try
        {
            var status = await runtime.GetStatusAsync(ct);
            runtimeStatus = status.Status.ToString();
            runtimeDetail = status.Detail;
        }
        catch (Exception ex)
        {
            runtimeStatus = "Offline";
            runtimeDetail = ex.Message;
        }

        var entries = report.Entries.ToDictionary(
            e => e.Key,
            e => new
            {
                status = e.Value.Status.ToString(),
                description = e.Value.Description,
                data = e.Value.Data
            });

        entries["runtime"] = new
        {
            status = runtimeStatus,
            description = runtimeDetail ?? "Runtime status checked",
            data = (IReadOnlyDictionary<string, object>)new Dictionary<string, object>()
        };

        var isHealthy = report.Status == HealthStatus.Healthy && runtimeStatus == "Online";
        return isHealthy ? Results.Ok(new { status = "Healthy", checks = entries, timestamp = DateTimeOffset.UtcNow })
            : Results.Ok(new { status = "Degraded", checks = entries, timestamp = DateTimeOffset.UtcNow });
    }
}
