<?php

declare(strict_types=1);

namespace App\Framework\Design\ValueObjects;

use App\Framework\Design\Analyzer\ColorAnalysisResult;
use App\Framework\Design\Analyzer\ComponentDetectionResult;
use App\Framework\Design\Analyzer\ConventionCheckResult;
use App\Framework\Design\Analyzer\TokenAnalysisResult;

/**
 * Complete Design System Analysis Result
 */
final readonly class DesignSystemAnalysis
{
    public function __construct(
        public TokenAnalysisResult $tokenAnalysis,
        public ColorAnalysisResult $colorAnalysis,
        public ComponentDetectionResult $componentAnalysis,
        public ConventionCheckResult $conventionAnalysis,
        public array $metadata = []
    ) {
    }

    public static function empty(): self
    {
        return new self(
            tokenAnalysis: new TokenAnalysisResult(0, [], [], [], [], [], []),
            colorAnalysis: new ColorAnalysisResult(0, [], [], [], [], []),
            componentAnalysis: new ComponentDetectionResult(0, [], [], [], [], []),
            conventionAnalysis: new ConventionCheckResult(100, [], [], [], 'none'),
            metadata: []
        );
    }

    /**
     * Gets the overall design system maturity level
     */
    public function getMaturityLevel(): string
    {
        $score = $this->getOverallDesignSystemScore();

        return match(true) {
            $score >= 90 => 'Mature',
            $score >= 70 => 'Established',
            $score >= 50 => 'Developing',
            $score >= 30 => 'Emerging',
            default => 'Basic'
        };
    }

    /**
     * Calculates overall design system score (0-100)
     */
    public function getOverallDesignSystemScore(): float
    {
        $tokenCoverage = $this->tokenAnalysis->getTokenCoverage();
        $tokenScore = $tokenCoverage['usage_percentage'] ?? 0;
        $colorScore = $this->colorAnalysis->getConsistencyScore();
        $componentScore = $this->componentAnalysis->getConsistencyScore();
        $conventionScore = $this->conventionAnalysis->overallScore;

        return ($tokenScore + $colorScore + $componentScore + $conventionScore) / 4;
    }

    /**
     * Gets critical issues that need immediate attention
     */
    public function getCriticalIssues(): array
    {
        $issues = [];

        // Token issues
        $tokenCoverage = $this->tokenAnalysis->getTokenCoverage();
        if (($tokenCoverage['usage_percentage'] ?? 0) < 30) {
            $issues[] = [
                'type' => 'tokens',
                'severity' => 'critical',
                'message' => 'Very low design token usage',
                'impact' => 'Inconsistent styling and maintenance difficulties',
            ];
        }

        // Color issues - check contrast compliance
        if ($this->colorAnalysis->getContrastComplianceScore() < 80) {
            $issues[] = [
                'type' => 'colors',
                'severity' => 'critical',
                'message' => 'WCAG accessibility violations found',
                'impact' => 'Poor accessibility for users',
            ];
        }

        // Convention issues
        if ($this->conventionAnalysis->overallScore < 40) {
            $issues[] = [
                'type' => 'conventions',
                'severity' => 'critical',
                'message' => 'Poor naming convention consistency',
                'impact' => 'Decreased developer productivity and maintenance',
            ];
        }

        return $issues;
    }

    /**
     * Gets quick wins for easy improvements
     */
    public function getQuickWins(): array
    {
        $wins = [];

        // Duplicate color removal
        if (count($this->colorAnalysis->duplicateColors) > 0) {
            $wins[] = [
                'type' => 'colors',
                'effort' => 'low',
                'impact' => 'medium',
                'message' => 'Remove duplicate color values',
                'action' => 'Consolidate ' . count($this->colorAnalysis->duplicateColors) . ' duplicate colors',
            ];
        }

        // Utility class organization based on pattern diversity
        if ($this->componentAnalysis->getPatternDiversity() > 80) {
            $wins[] = [
                'type' => 'components',
                'effort' => 'low',
                'impact' => 'high',
                'message' => 'Standardize component patterns',
                'action' => 'Choose one primary CSS methodology for better consistency',
            ];
        }

        return $wins;
    }

    /**
     * Gets development roadmap based on analysis
     */
    public function getDevelopmentRoadmap(): array
    {
        $roadmap = [];

        $score = $this->getOverallDesignSystemScore();

        if ($score < 30) {
            $roadmap[] = [
                'phase' => 1,
                'title' => 'Foundation Setup',
                'priority' => 'critical',
                'tasks' => [
                    'Establish core design tokens',
                    'Define color palette',
                    'Set naming conventions',
                    'Create basic component library',
                ],
                'timeline' => '2-4 weeks',
            ];
        }

        if ($score >= 30 && $score < 60) {
            $roadmap[] = [
                'phase' => 2,
                'title' => 'System Expansion',
                'priority' => 'high',
                'tasks' => [
                    'Expand token coverage',
                    'Improve component organization',
                    'Add responsive design tokens',
                    'Implement consistent spacing scale',
                ],
                'timeline' => '4-6 weeks',
            ];
        }

        if ($score >= 60) {
            $roadmap[] = [
                'phase' => 3,
                'title' => 'Optimization & Polish',
                'priority' => 'medium',
                'tasks' => [
                    'Optimize token usage',
                    'Refine component APIs',
                    'Add advanced theming',
                    'Implement design system documentation',
                ],
                'timeline' => '6-8 weeks',
            ];
        }

        return $roadmap;
    }

    /**
     * Exports analysis as array for JSON serialization
     */
    public function exportReport(): array
    {
        return [
            'overall_score' => $this->getOverallDesignSystemScore(),
            'maturity_level' => $this->getMaturityLevel(),
            'critical_issues' => $this->getCriticalIssues(),
            'quick_wins' => $this->getQuickWins(),
            'roadmap' => $this->getDevelopmentRoadmap(),
            'detailed_analysis' => [
                'tokens' => $this->tokenAnalysis->toArray(),
                'colors' => $this->colorAnalysis->toArray(),
                'components' => $this->componentAnalysis->toArray(),
                'conventions' => $this->conventionAnalysis->toArray(),
            ],
            'metadata' => array_merge($this->metadata, [
                'generated_at' => date('c'),
                'version' => '1.0',
            ]),
        ];
    }
}
