<?php

declare(strict_types=1);

namespace App\Services\Baselines\SnapshotRendering;

use Illuminate\Support\Str;

final readonly class GapSummary
{
    /**
     * @param  list<string>  $messages
     */
    public function __construct(
        public int $count = 0,
        public array $messages = [],
    ) {}

    public static function none(): self
    {
        return new self;
    }

    /**
     * @param  array<string, mixed>  $meta
     */
    public static function fromItemMeta(array $meta, FidelityState $fidelity, bool $usesFallback = false): self
    {
        $messages = [];

        $warnings = $meta['warnings'] ?? null;

        if (is_array($warnings)) {
            foreach ($warnings as $warning) {
                if (is_string($warning) && trim($warning) !== '') {
                    $messages[] = trim($warning);
                }
            }
        }

        if ($fidelity === FidelityState::ReferenceOnly) {
            $messages[] = 'Metadata-only evidence was captured for this item.';
        }

        if ($fidelity === FidelityState::Unsupported || $usesFallback) {
            $messages[] = 'A fallback renderer is being used for this item.';
        }

        $messages = self::uniqueMessages($messages);

        return new self(
            count: 0,
            messages: $messages,
        );
    }

    /**
     * @param  array<string, int>  $reasons
     */
    public static function fromReasonMap(array $reasons): self
    {
        $messages = [];
        $primaryCount = 0;

        foreach ($reasons as $reason => $reasonCount) {
            if (! is_string($reason) || ! is_numeric($reasonCount) || (int) $reasonCount <= 0) {
                continue;
            }

            if (self::isDiagnosticReason($reason)) {
                $messages[] = sprintf('%s (%d)', self::diagnosticMessageForReason($reason), (int) $reasonCount);

                continue;
            }

            $messages[] = sprintf('%s (%d)', self::humanizeReason($reason), (int) $reasonCount);
            $primaryCount += (int) $reasonCount;
        }

        return new self(
            count: $primaryCount,
            messages: self::uniqueMessages($messages),
        );
    }

    /**
     * @param  array<int, self>  $summaries
     */
    public static function merge(array $summaries): self
    {
        $count = 0;
        $messages = [];

        foreach ($summaries as $summary) {
            $count += $summary->count;
            $messages = [...$messages, ...$summary->messages];
        }

        $messages = self::uniqueMessages($messages);

        return new self(
            count: $count,
            messages: $messages,
        );
    }

    public function withMessage(string $message): self
    {
        $message = trim($message);

        if ($message === '') {
            return $this;
        }

        $messages = self::uniqueMessages([...$this->messages, $message]);

        return new self(
            count: $this->count,
            messages: $messages,
        );
    }

    public function hasGaps(): bool
    {
        return $this->count > 0;
    }

    public function badgeState(): string
    {
        return $this->hasGaps() ? 'gaps_present' : 'clear';
    }

    /**
     * @return array{count: int, has_gaps: bool, messages: list<string>, badge_state: string}
     */
    public function toArray(): array
    {
        return [
            'count' => $this->count,
            'has_gaps' => $this->hasGaps(),
            'messages' => $this->messages,
            'badge_state' => $this->badgeState(),
        ];
    }

    /**
     * @param  list<string>  $messages
     * @return list<string>
     */
    private static function uniqueMessages(array $messages): array
    {
        return array_values(array_unique(array_values(array_filter(
            array_map(static fn (string $message): string => trim($message), $messages),
            static fn (string $message): bool => $message !== '',
        ))));
    }

    private static function humanizeReason(string $reason): string
    {
        return Str::of($reason)
            ->replace(['_', '-'], ' ')
            ->headline()
            ->toString();
    }

    private static function isDiagnosticReason(string $reason): bool
    {
        return in_array($reason, ['meta_fallback'], true);
    }

    private static function diagnosticMessageForReason(string $reason): string
    {
        return match ($reason) {
            'meta_fallback' => 'Metadata-only evidence was used for some items.',
            default => self::humanizeReason($reason),
        };
    }
}
