<?php

declare(strict_types=1);

namespace App\Framework\Design\Analyzer;

use App\Framework\Design\ValueObjects\CssParseResult;
use App\Framework\Filesystem\ValueObjects\FilePath;

/**
 * Vollständige Design System Analyse - Haupt-Ergebnis-Klasse
 */
final readonly class DesignSystemAnalysis
{
    /**
     * @param FilePath[] $sourceFiles
     * @param CssParseResult[] $parseResults
     */
    public function __construct(
        public array $sourceFiles,
        public array $parseResults,
        public CssParseResult $combinedResult,
        public TokenAnalysisResult $tokenAnalysis,
        public ComponentDetectionResult $componentAnalysis,
        public ConventionCheckResult $conventionAnalysis,
        public ColorAnalysisResult $colorAnalysis,
        public array $overallStatistics
    ) {
    }

    /**
     * Berechnet Gesamt-Design-System-Score (0-100)
     */
    public function getOverallDesignSystemScore(): int
    {
        $scores = [
            'tokens' => $this->getTokenScore(),
            'components' => $this->getComponentScore(),
            'conventions' => $this->conventionAnalysis->overallScore,
            'colors' => $this->getColorScore(),
        ];

        // Gewichtung der verschiedenen Bereiche
        $weights = [
            'tokens' => 0.25,
            'components' => 0.25,
            'conventions' => 0.30,
            'colors' => 0.20,
        ];

        $weightedScore = 0;
        foreach ($scores as $area => $score) {
            $weightedScore += $score * $weights[$area];
        }

        return (int) round($weightedScore);
    }

    /**
     * Gibt die Reife-Stufe des Design Systems zurück
     */
    public function getMaturityLevel(): string
    {
        $score = $this->getOverallDesignSystemScore();
        $tokenUsage = $this->tokenAnalysis->getTokenCoverage()['usage_percentage'];
        $hasComponents = $this->componentAnalysis->totalComponents > 0;
        $colorConsistency = $this->colorAnalysis->getConsistencyScore();

        return match(true) {
            $score >= 90 && $tokenUsage >= 80 && $hasComponents && $colorConsistency >= 80 => 'mature',
            $score >= 75 && $tokenUsage >= 60 && $hasComponents => 'established',
            $score >= 60 && ($tokenUsage >= 40 || $hasComponents) => 'developing',
            $score >= 40 => 'emerging',
            default => 'basic'
        };
    }

    /**
     * Gibt kritische Problembereiche zurück
     */
    public function getCriticalIssues(): array
    {
        $issues = [];

        // Token-Probleme
        if ($this->tokenAnalysis->totalTokens === 0) {
            $issues[] = [
                'severity' => 'high',
                'category' => 'tokens',
                'issue' => 'No design tokens found',
                'impact' => 'Inconsistent styling and difficult maintenance',
                'recommendation' => 'Implement CSS custom properties for colors, spacing, and typography',
            ];
        } elseif (count($this->tokenAnalysis->unusedTokens) > $this->tokenAnalysis->totalTokens * 0.5) {
            $issues[] = [
                'severity' => 'medium',
                'category' => 'tokens',
                'issue' => 'Many unused design tokens',
                'impact' => 'Bloated CSS and confusing token system',
                'recommendation' => 'Remove unused tokens and audit token usage',
            ];
        }

        // Component-Probleme
        if ($this->componentAnalysis->getConsistencyScore() < 50) {
            $issues[] = [
                'severity' => 'high',
                'category' => 'components',
                'issue' => 'Inconsistent component patterns',
                'impact' => 'Poor maintainability and team confusion',
                'recommendation' => 'Standardize on one CSS methodology (BEM, Utility-first, etc.)',
            ];
        }

        // Convention-Probleme
        $highSeverityViolations = $this->conventionAnalysis->getViolationsBySeverity()['high'];
        if (! empty($highSeverityViolations)) {
            $issues[] = [
                'severity' => 'high',
                'category' => 'conventions',
                'issue' => count($highSeverityViolations) . ' high-severity convention violations',
                'impact' => 'Accessibility and usability problems',
                'recommendation' => 'Address accessibility issues, especially focus styles and contrast',
            ];
        }

        // Farb-Probleme
        $worstContrastPairs = $this->colorAnalysis->getWorstContrastPairs();
        if (! empty($worstContrastPairs)) {
            $issues[] = [
                'severity' => 'high',
                'category' => 'colors',
                'issue' => count($worstContrastPairs) . ' color combinations fail WCAG contrast requirements',
                'impact' => 'Poor accessibility for users with visual impairments',
                'recommendation' => 'Improve color contrast ratios to meet WCAG AA standards',
            ];
        }

        return $issues;
    }

    /**
     * Gibt Quick-Win-Verbesserungen zurück
     */
    public function getQuickWins(): array
    {
        $quickWins = [];

        // Duplikate entfernen
        if (! empty($this->colorAnalysis->duplicateColors)) {
            $totalDuplicates = array_sum(array_column($this->colorAnalysis->duplicateColors, 'potential_savings'));
            $quickWins[] = [
                'effort' => 'low',
                'impact' => 'medium',
                'action' => "Remove {$totalDuplicates} duplicate colors",
                'benefit' => 'Smaller CSS size and cleaner color palette',
                'estimated_time' => '1-2 hours',
            ];
        }

        // Unbenutzte Tokens
        if (count($this->tokenAnalysis->unusedTokens) > 0) {
            $unusedCount = count($this->tokenAnalysis->unusedTokens);
            $quickWins[] = [
                'effort' => 'low',
                'impact' => 'low',
                'action' => "Remove {$unusedCount} unused design tokens",
                'benefit' => 'Cleaner token system and reduced CSS complexity',
                'estimated_time' => '30 minutes',
            ];
        }

        // Naming-Konventionen
        if ($this->conventionAnalysis->categoryScores['naming'] < 70) {
            $quickWins[] = [
                'effort' => 'medium',
                'impact' => 'high',
                'action' => 'Standardize CSS class naming conventions',
                'benefit' => 'Better maintainability and team consistency',
                'estimated_time' => '2-4 hours',
            ];
        }

        // Fehlende Standard-Tokens
        if (! empty($this->tokenAnalysis->missingTokens)) {
            $quickWins[] = [
                'effort' => 'medium',
                'impact' => 'high',
                'action' => 'Add missing standard design tokens',
                'benefit' => 'More complete design system and better consistency',
                'estimated_time' => '1-3 hours',
            ];
        }

        return $quickWins;
    }

    /**
     * Gibt Entwicklungsroadmap zurück
     */
    public function getDevelopmentRoadmap(): array
    {
        $maturity = $this->getMaturityLevel();

        $roadmap = match($maturity) {
            'basic' => [
                'phase_1' => [
                    'title' => 'Foundation Setup',
                    'duration' => '1-2 weeks',
                    'tasks' => [
                        'Establish CSS custom properties for core colors',
                        'Define basic spacing scale',
                        'Standardize naming conventions',
                        'Create utility classes for common patterns',
                    ],
                ],
                'phase_2' => [
                    'title' => 'Component Library',
                    'duration' => '2-3 weeks',
                    'tasks' => [
                        'Build core component patterns',
                        'Document component usage',
                        'Implement accessibility standards',
                        'Create component naming guidelines',
                    ],
                ],
            ],
            'emerging' => [
                'phase_1' => [
                    'title' => 'Standardization',
                    'duration' => '1 week',
                    'tasks' => [
                        'Fix critical accessibility issues',
                        'Consolidate duplicate colors',
                        'Improve token usage consistency',
                        'Document existing patterns',
                    ],
                ],
                'phase_2' => [
                    'title' => 'Enhancement',
                    'duration' => '2 weeks',
                    'tasks' => [
                        'Expand design token system',
                        'Improve component consistency',
                        'Add semantic color tokens',
                        'Create design guidelines',
                    ],
                ],
            ],
            'developing' => [
                'phase_1' => [
                    'title' => 'Optimization',
                    'duration' => '3-5 days',
                    'tasks' => [
                        'Remove unused tokens and styles',
                        'Improve color contrast compliance',
                        'Optimize component patterns',
                        'Enhance documentation',
                    ],
                ],
            ],
            'established' => [
                'phase_1' => [
                    'title' => 'Advanced Features',
                    'duration' => '1 week',
                    'tasks' => [
                        'Implement advanced color formats (OKLCH)',
                        'Create automated design token generation',
                        'Add theme switching capabilities',
                        'Implement design system automation',
                    ],
                ],
            ],
            'mature' => [
                'phase_1' => [
                    'title' => 'Maintenance & Innovation',
                    'duration' => 'Ongoing',
                    'tasks' => [
                        'Monitor design system metrics',
                        'Implement advanced automation',
                        'Research emerging CSS features',
                        'Mentor other teams',
                    ],
                ],
            ]
        };

        return [
            'current_maturity' => $maturity,
            'next_level' => $this->getNextMaturityLevel($maturity),
            'phases' => $roadmap,
        ];
    }

    /**
     * Exportiert vollständigen Report
     */
    public function exportReport(): array
    {
        return [
            'meta' => [
                'generated_at' => date('c'),
                'analyzed_files' => count($this->sourceFiles),
                'total_css_size' => $this->overallStatistics['total_content_size'],
                'analysis_version' => '1.0',
            ],
            'summary' => [
                'overall_score' => $this->getOverallDesignSystemScore(),
                'maturity_level' => $this->getMaturityLevel(),
                'critical_issues_count' => count($this->getCriticalIssues()),
                'quick_wins_count' => count($this->getQuickWins()),
            ],
            'detailed_analysis' => [
                'token_analysis' => $this->tokenAnalysis->toArray(),
                'component_analysis' => $this->componentAnalysis->toArray(),
                'convention_analysis' => $this->conventionAnalysis->toArray(),
                'color_analysis' => $this->colorAnalysis->toArray(),
            ],
            'recommendations' => [
                'critical_issues' => $this->getCriticalIssues(),
                'quick_wins' => $this->getQuickWins(),
                'development_roadmap' => $this->getDevelopmentRoadmap(),
            ],
            'statistics' => $this->overallStatistics,
        ];
    }

    /**
     * Berechnet Token-Score
     */
    private function getTokenScore(): int
    {
        if ($this->tokenAnalysis->totalTokens === 0) {
            return 0;
        }

        $coverage = $this->tokenAnalysis->getTokenCoverage()['usage_percentage'];
        $missingTokenPenalty = count($this->tokenAnalysis->missingTokens) * 5;

        return max(0, (int) ($coverage - $missingTokenPenalty));
    }

    /**
     * Berechnet Component-Score
     */
    private function getComponentScore(): int
    {
        if ($this->componentAnalysis->totalComponents === 0) {
            return 20; // Basis-Score für keine Components
        }

        $consistency = $this->componentAnalysis->getConsistencyScore();
        $diversity = 100 - $this->componentAnalysis->getPatternDiversity(); // Weniger Diversity ist besser für Konsistenz

        return (int) (($consistency * 0.7) + ($diversity * 0.3));
    }

    /**
     * Berechnet Color-Score
     */
    private function getColorScore(): int
    {
        if ($this->colorAnalysis->totalColors === 0) {
            return 30; // Basis-Score für keine Farben
        }

        $consistency = $this->colorAnalysis->getConsistencyScore();
        $contrastCompliance = $this->colorAnalysis->getContrastComplianceScore();

        return (int) (($consistency * 0.4) + ($contrastCompliance * 0.6));
    }

    /**
     * Bestimmt nächste Reife-Stufe
     */
    private function getNextMaturityLevel(string $current): string
    {
        return match($current) {
            'basic' => 'emerging',
            'emerging' => 'developing',
            'developing' => 'established',
            'established' => 'mature',
            'mature' => 'mature', // Already at top level
            default => 'emerging'
        };
    }
}
