<?php

declare(strict_types=1);

namespace App\Framework\Design\Service;

use App\Framework\Design\Parser\CssParser;
use App\Framework\Design\Parser\CssParseResult;
use App\Framework\Design\ValueObjects\DesignSystemAnalysis;
use App\Framework\Filesystem\ValueObjects\FilePath;

/**
 * Design System Analyzer Service
 */
final readonly class DesignSystemAnalyzer
{
    public function __construct(
        private CssParser $parser,
        private TokenAnalyzer $tokenAnalyzer,
        private ComponentDetector $componentDetector,
        private ConventionChecker $conventionChecker,
        private ColorAnalyzer $colorAnalyzer
    ) {
    }

    /**
     * Analysiert ein Array von CSS-Dateien
     *
     * @param FilePath[] $cssFiles
     */
    public function analyze(array $cssFiles): DesignSystemAnalysis
    {
        if (empty($cssFiles)) {
            return $this->createEmptyAnalysis();
        }

        $parseResults = [];
        $allRules = [];
        $allCustomProperties = [];
        $allClassNames = [];
        $totalContentSize = 0;

        // Parse alle CSS-Dateien
        foreach ($cssFiles as $cssFile) {
            $parseResult = $this->parser->parseFile($cssFile);
            $parseResults[] = $parseResult;

            $allRules = array_merge($allRules, $parseResult->rules);
            $allCustomProperties = array_merge($allCustomProperties, $parseResult->customProperties);
            $allClassNames = array_merge($allClassNames, $parseResult->classNames);

            $totalContentSize += strlen($parseResult->rawContent);
        }

        // Erstelle kombiniertes Ergebnis
        $combinedResult = new CssParseResult(
            sourceFile: null,
            rules: $allRules,
            customProperties: $allCustomProperties,
            classNames: $allClassNames,
            rawContent: '', // Combined content not available
            statistics: [
                'total_rules' => count($allRules),
                'total_custom_properties' => count($allCustomProperties),
                'total_classes' => count($allClassNames),
            ]
        );

        // Führe alle Analysen durch
        $tokenAnalysis = $this->tokenAnalyzer->analyzeTokens($combinedResult);
        $componentAnalysis = $this->componentDetector->detectComponents($combinedResult);
        $conventionAnalysis = $this->conventionChecker->checkConventions($combinedResult);
        $colorAnalysis = $this->colorAnalyzer->analyzeColors($combinedResult);

        $overallStatistics = [
            'analyzed_files' => count($cssFiles),
            'total_rules' => count($allRules),
            'total_custom_properties' => count($allCustomProperties),
            'total_class_names' => count($allClassNames),
            'total_content_size' => $totalContentSize,
            'analysis_timestamp' => time(),
        ];

        return new DesignSystemAnalysis(
            tokenAnalysis: $tokenAnalysis,
            colorAnalysis: $colorAnalysis,
            componentAnalysis: $componentAnalysis,
            conventionAnalysis: $conventionAnalysis,
            metadata: $overallStatistics
        );
    }

    /**
     * Analysiert eine einzelne CSS-Datei
     */
    public function analyzeFile(FilePath $cssFile): DesignSystemAnalysis
    {
        return $this->analyze([$cssFile]);
    }

    /**
     * Analysiert CSS-Content direkt
     */
    public function analyzeContent(string $cssContent, ?FilePath $sourceFile = null): DesignSystemAnalysis
    {
        $parseResult = $this->parser->parseContent($cssContent, $sourceFile);

        $tokenAnalysis = $this->tokenAnalyzer->analyzeTokens($parseResult);
        $componentAnalysis = $this->componentDetector->detectComponents($parseResult);
        $conventionAnalysis = $this->conventionChecker->checkConventions($parseResult);
        $colorAnalysis = $this->colorAnalyzer->analyzeColors($parseResult);

        $overallStatistics = [
            'analyzed_files' => $sourceFile ? 1 : 0,
            'total_rules' => count($parseResult->rules),
            'total_custom_properties' => count($parseResult->customProperties),
            'total_class_names' => count($parseResult->classNames),
            'total_content_size' => strlen($parseResult->rawContent),
            'analysis_timestamp' => time(),
        ];

        return new DesignSystemAnalysis(
            tokenAnalysis: $tokenAnalysis,
            colorAnalysis: $colorAnalysis,
            componentAnalysis: $componentAnalysis,
            conventionAnalysis: $conventionAnalysis,
            metadata: $overallStatistics
        );
    }

    /**
     * Erstellt leere Analyse für den Fall dass keine Dateien vorhanden
     */
    private function createEmptyAnalysis(): DesignSystemAnalysis
    {
        $emptyParseResult = new CssParseResult(
            sourceFile: null,
            rules: [],
            customProperties: [],
            classNames: [],
            rawContent: '',
            statistics: [
                'total_rules' => 0,
                'total_custom_properties' => 0,
                'total_classes' => 0,
            ]
        );

        $tokenAnalysis = $this->tokenAnalyzer->analyzeTokens($emptyParseResult);
        $componentAnalysis = $this->componentDetector->detectComponents($emptyParseResult);
        $conventionAnalysis = $this->conventionChecker->checkConventions($emptyParseResult);
        $colorAnalysis = $this->colorAnalyzer->analyzeColors($emptyParseResult);

        return new DesignSystemAnalysis(
            tokenAnalysis: $tokenAnalysis,
            colorAnalysis: $colorAnalysis,
            componentAnalysis: $componentAnalysis,
            conventionAnalysis: $conventionAnalysis,
            metadata: [
                'analyzed_files' => 0,
                'total_rules' => 0,
                'total_custom_properties' => 0,
                'total_class_names' => 0,
                'total_content_size' => 0,
                'analysis_timestamp' => time(),
            ]
        );
    }
}
