<?php

declare(strict_types=1);

namespace App\Framework\Process\ValueObjects\Docker;

use App\Framework\Core\ValueObjects\Byte;
use App\Framework\Core\ValueObjects\Percentage;

/**
 * Docker Container Statistics.
 */
final readonly class DockerContainerStats
{
    public function __construct(
        public string $containerId,
        public string $containerName,
        public Percentage $cpuPercent,
        public Byte $memoryUsage,
        public Byte $memoryLimit,
        public Percentage $memoryPercent,
        public Byte $networkIn,
        public Byte $networkOut,
        public Byte $blockIn,
        public Byte $blockOut
    ) {
    }

    /**
     * Erstellt Stats aus Docker-Output.
     */
    public static function fromDockerStats(
        string $containerId,
        string $containerName,
        float $cpuPercent,
        int $memoryUsageBytes,
        int $memoryLimitBytes,
        int $networkInBytes,
        int $networkOutBytes,
        int $blockInBytes,
        int $blockOutBytes
    ): self {
        $memoryPercent = $memoryLimitBytes > 0
            ? ($memoryUsageBytes / $memoryLimitBytes) * 100
            : 0.0;

        return new self(
            containerId: $containerId,
            containerName: $containerName,
            cpuPercent: Percentage::from($cpuPercent),
            memoryUsage: Byte::fromBytes($memoryUsageBytes),
            memoryLimit: Byte::fromBytes($memoryLimitBytes),
            memoryPercent: Percentage::from($memoryPercent),
            networkIn: Byte::fromBytes($networkInBytes),
            networkOut: Byte::fromBytes($networkOutBytes),
            blockIn: Byte::fromBytes($blockInBytes),
            blockOut: Byte::fromBytes($blockOutBytes)
        );
    }

    /**
     * Konvertiert zu Array.
     *
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'container_id' => $this->containerId,
            'container_name' => $this->containerName,
            'cpu_percent' => $this->cpuPercent->format(2),
            'memory_usage' => $this->memoryUsage->toHumanReadable(),
            'memory_limit' => $this->memoryLimit->toHumanReadable(),
            'memory_percent' => $this->memoryPercent->format(2),
            'network_in' => $this->networkIn->toHumanReadable(),
            'network_out' => $this->networkOut->toHumanReadable(),
            'block_in' => $this->blockIn->toHumanReadable(),
            'block_out' => $this->blockOut->toHumanReadable(),
        ];
    }
}
