package com.cameleer.server.app.dto;

import com.cameleer.server.core.agent.AgentInfo;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;

import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;

@Schema(description = "Agent instance summary with runtime metrics")
public record AgentInstanceResponse(
        @NotNull String instanceId,
        @NotNull String displayName,
        @NotNull String applicationId,
        String environmentId,
        @NotNull String status,
        @NotNull List<String> routeIds,
        @NotNull Instant registeredAt,
        @NotNull Instant lastHeartbeat,
        String version,
        Map<String, Object> capabilities,
        double tps,
        double errorRate,
        int activeRoutes,
        int totalRoutes,
        long uptimeSeconds,
        @Schema(description = "Recent average CPU usage (0.0–1.0), -1 if unavailable") double cpuUsage
) {
    public static AgentInstanceResponse from(AgentInfo info) {
        long uptime = Duration.between(info.registeredAt(), Instant.now()).toSeconds();
        return new AgentInstanceResponse(
                info.instanceId(), info.displayName(), info.applicationId(),
                info.environmentId(),
                info.state().name(), info.routeIds(),
                info.registeredAt(), info.lastHeartbeat(),
                info.version(), info.capabilities(),
                0.0, 0.0,
                0, info.routeIds() != null ? info.routeIds().size() : 0,
                uptime, -1
        );
    }

    public AgentInstanceResponse withMetrics(double tps, double errorRate, int activeRoutes) {
        return new AgentInstanceResponse(
                instanceId, displayName, applicationId, environmentId,
                status, routeIds, registeredAt, lastHeartbeat,
                version, capabilities,
                tps, errorRate, activeRoutes, totalRoutes, uptimeSeconds, cpuUsage
        );
    }

    public AgentInstanceResponse withCpuUsage(double cpuUsage) {
        return new AgentInstanceResponse(
                instanceId, displayName, applicationId, environmentId,
                status, routeIds, registeredAt, lastHeartbeat,
                version, capabilities,
                tps, errorRate, activeRoutes, totalRoutes, uptimeSeconds, cpuUsage
        );
    }
}
