using System.Runtime.InteropServices;
using FastEndpoints;
using SpaceGame.Api.Universe.Simulation;

namespace SpaceGame.Api.Universe.Api;

public sealed class GetTelemetryHandler(TelemetryService telemetry, WorldService worldService) : EndpointWithoutRequest
{
    public override void Configure()
    {
        Get("/api/telemetry");
        Policies(AuthPolicyNames.GmAccess);
    }

    public override Task HandleAsync(CancellationToken cancellationToken)
    {
        var status = worldService.GetStatus();
        var connections = worldService.GetConnectionStats();
        var uptime = telemetry.Uptime;

        return SendOkAsync(new
        {
            process = new
            {
                uptimeSeconds = uptime.TotalSeconds,
                cpuPercent = Math.Round(telemetry.CpuPercent, 1),
                workingSetMb = Math.Round(telemetry.WorkingSetBytes / 1_048_576.0, 1),
                gcMemoryMb = Math.Round(telemetry.GcMemoryBytes / 1_048_576.0, 1),
                threadCount = telemetry.ThreadCount,
                processorCount = Environment.ProcessorCount,
            },
            simulation = new
            {
                sequence = status.Sequence,
                connectedClients = connections.ConnectedClients,
                deltaHistoryCount = connections.DeltaHistoryCount,
                tickIntervalMs = 200,
            },
            runtime = new
            {
                frameworkDescription = RuntimeInformation.FrameworkDescription,
                osDescription = RuntimeInformation.OSDescription,
                gcGen0 = GC.CollectionCount(0),
                gcGen1 = GC.CollectionCount(1),
                gcGen2 = GC.CollectionCount(2),
            },
        }, cancellationToken);
    }
}
