using Nexus.Api.Data;
using Nexus.Api.Services;

namespace Nexus.Api.Routing;

public sealed record RoutingTarget(
    int Priority,
    string Provider,
    string Model,
    string Purpose,
    OperationalStatus Status,
    string Detail);

public sealed class ModelRoutingService(
    IOpenClawControlService openClaw)
{
    public async Task<IReadOnlyCollection<RoutingTarget>> GetStatusAsync(
        CancellationToken cancellationToken)
    {
        var response = await openClaw.GetModelsAsync(cancellationToken);
        if (response.Items.Count == 0)
            return Array.Empty<RoutingTarget>();

        return response.Items
            .OrderByDescending(model =>
                string.Equals(model.Provider, "openai", StringComparison.OrdinalIgnoreCase))
            .ThenBy(model => model.Name, StringComparer.OrdinalIgnoreCase)
            .Select((model, index) => new RoutingTarget(
                index + 1,
                $"OpenClaw / {model.Provider}",
                model.Id,
                string.Equals(model.Provider, "openai", StringComparison.OrdinalIgnoreCase)
                    ? "Primary agent runtime"
                    : "Configured Gateway fallback",
                model.Available ? OperationalStatus.Online : OperationalStatus.Degraded,
                model.Available
                    ? "Configured and resolved by OpenClaw"
                    : model.Reason ?? "Configured in OpenClaw, currently unavailable"))
            .ToArray();
    }
}
