<?php

declare(strict_types=1);

namespace App\Framework\Design\Analyzer;

/**
 * Ergebnis der Token-Analyse
 */
final readonly class TokenAnalysisResult
{
    public function __construct(
        public int $totalTokens,
        public array $tokensByType,
        public array $tokenHierarchy,
        public array $unusedTokens,
        public array $missingTokens,
        public array $tokenUsage,
        public array $recommendations,
        public array $usedTokens = []
    ) {
    }

    /**
     * Gibt die häufigsten Token-Typen zurück
     * @return array<string, int>
     */
    public function getMostUsedTokenTypes(): array
    {
        $usage = [];

        foreach ($this->tokensByType as $type => $data) {
            $usage[$type] = $data['count'];
        }

        arsort($usage);

        return $usage;
    }

    /**
     * Gibt Token-Coverage-Statistiken zurück
     * @return array<string, int|float>
     */
    public function getTokenCoverage(): array
    {
        $usedTokens = count($this->tokenUsage);
        $totalTokens = $this->totalTokens;

        return [
            'used_tokens' => $usedTokens,
            'unused_tokens' => count($this->unusedTokens),
            'total_tokens' => $totalTokens,
            'usage_percentage' => $totalTokens > 0 ? round(($usedTokens / $totalTokens) * 100, 1) : 0,
        ];
    }

    /**
     * Gibt Empfehlungs-Prioritäten zurück
     * @return array<int, array<string, string>>
     */
    public function getRecommendationPriorities(): array
    {
        $priorities = [];

        foreach ($this->recommendations as $recommendation) {
            if (str_contains($recommendation, 'Remove')) {
                $priorities[] = ['level' => 'high', 'text' => $recommendation];
            } elseif (str_contains($recommendation, 'Consider adding')) {
                $priorities[] = ['level' => 'medium', 'text' => $recommendation];
            } else {
                $priorities[] = ['level' => 'low', 'text' => $recommendation];
            }
        }

        return $priorities;
    }

    /**
     * Konvertiert zu Array für Export
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'total_tokens' => $this->totalTokens,
            'tokens_by_type' => $this->tokensByType,
            'token_hierarchy' => $this->tokenHierarchy,
            'unused_tokens' => array_map(fn ($token) => $token->toArray(), $this->unusedTokens),
            'missing_tokens' => $this->missingTokens,
            'token_usage' => $this->tokenUsage,
            'recommendations' => $this->recommendations,
            'coverage' => $this->getTokenCoverage(),
            'priorities' => $this->getRecommendationPriorities(),
        ];
    }
}
