<?php

declare(strict_types=1);

namespace BotGuard\Services\Detection;

/**
 * The aggregate result of running the detection engine over a SignalBag.
 *
 * Carries the final 0-100 score, the classification band, the action to take,
 * and the individual ModuleResults for logging and the analytics breakdown.
 */
final class DetectionOutcome
{
    /**
     * @param int             $score          Final human score, 0-100.
     * @param string          $classification human|suspicious|bot
     * @param string          $action         redirect_primary|redirect_alternate|block|allow
     * @param ModuleResult[]  $results        Per-module results (enabled modules only).
     * @param array<string,float> $weights    module key => weight used.
     */
    public function __construct(
        public readonly int $score,
        public readonly string $classification,
        public readonly string $action,
        public readonly array $results,
        public readonly array $weights,
    ) {
    }

    public function isHuman(): bool
    {
        return $this->classification === 'human';
    }

    public function isBot(): bool
    {
        return $this->classification === 'bot';
    }

    /**
     * Flattened per-module summary for storage in verification_results.breakdown.
     *
     * @return array<string, array<string, mixed>>
     */
    public function breakdown(): array
    {
        $out = [];

        foreach ($this->results as $result) {
            $weight = $this->weights[$result->key] ?? 0.0;
            $out[$result->key] = [
                'score'    => round($result->score, 4),
                'weight'   => $weight,
                'weighted' => round($result->score * $weight, 2),
                'passed'   => $result->passed,
                'failed'   => $result->failed,
            ];
        }

        return $out;
    }

    /**
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'score'          => $this->score,
            'classification' => $this->classification,
            'action'         => $this->action,
            'breakdown'      => $this->breakdown(),
        ];
    }
}
