<?php

declare(strict_types=1);

namespace App\Framework\DDoS\Components;

use App\Framework\CircuitBreaker\CircuitBreakerInterface;
use App\Framework\Logging\Logger;

/**
 * Analyzes service health using CircuitBreaker metrics
 */
final class ServiceHealthAnalyzer
{
    /**
     * Default services to monitor
     */
    private array $monitoredServices = ['web', 'api', 'database'];

    public function __construct(
        private readonly CircuitBreakerInterface $circuitBreaker,
        private readonly Logger $logger,
        private readonly ?array $services = null
    ) {
    }

    /**
     * Analyze service health using CircuitBreaker
     *
     * @param string $clientIp The client IP address (for context logging)
     * @return array Analysis results with health scores and degraded services
     */
    public function analyzeServiceHealth(string $clientIp): array
    {
        $services = $this->services ?? $this->monitoredServices;
        $healthScores = [];

        foreach ($services as $service) {
            try {
                $metrics = $this->circuitBreaker->getMetrics($service);
                $healthScores[$service] = $this->calculateHealthScore($metrics);
            } catch (\Throwable $e) {
                $healthScores[$service] = 0.5; // Neutral when unavailable
                $this->logger->warning("Circuit breaker metrics unavailable for {$service}", [
                    'error' => $e->getMessage(),
                    'client_ip' => $clientIp,
                ]);
            }
        }

        $overallHealth = count($healthScores) > 0
            ? array_sum($healthScores) / count($healthScores)
            : 0.0;

        $degradedServices = array_filter($healthScores, fn ($score) => $score > 0.7);

        $this->logger->debug('Service health analysis', [
            'overall_health' => $overallHealth,
            'degraded_services_count' => count($degradedServices),
        ]);

        return [
            'overall_health' => $overallHealth,
            'service_scores' => $healthScores,
            'degraded_services' => $degradedServices,
            'confidence' => 0.9, // High confidence in circuit breaker data
            'threat_score' => $overallHealth, // Higher score = more degraded
        ];
    }

    /**
     * Calculate health score from circuit breaker metrics
     *
     * @param \App\Framework\CircuitBreaker\CircuitBreakerMetrics $metrics Circuit breaker metrics
     * @return float Health score (0.0-1.0, higher is worse)
     */
    private function calculateHealthScore(\App\Framework\CircuitBreaker\CircuitBreakerMetrics $metrics): float
    {
        $totalRequests = max(1, $metrics->failureCount + $metrics->successCount);
        $failureRate = $metrics->failureCount / $totalRequests;

        // Convert to 0-1 threat score (higher means more degraded)
        return min(1.0, $failureRate * 2.0);
    }
}
