<?php

declare(strict_types=1);

namespace App\Framework\View\Caching;

use App\Framework\Cache\Cache;
use App\Framework\View\Caching\Analysis\TemplateAnalyzer;

class CacheDiagnostics
{
    private array $metrics = [];

    public function __construct(
        private CacheManager $cacheManager,
        private TemplateAnalyzer $analyzer,
        private Cache $cache
    ) {
    }

    public function getPerformanceReport(): array
    {
        return [
            'cache_hit_rate' => $this->calculateHitRate(),
            'average_render_time' => $this->getAverageRenderTime(),
            'cache_size' => $this->getCacheSize(),
            'most_cached_templates' => $this->getMostCachedTemplates(),
            'cache_strategy_distribution' => $this->getStrategyDistribution(),
            'memory_usage' => $this->getMemoryUsage(),
            'recommendations' => $this->generateRecommendations(),
        ];
    }

    public function analyzeTemplate(string $template): array
    {
        $analysis = $this->analyzer->analyze($template);

        return [
            'template' => $template,
            'recommended_strategy' => $analysis->recommendedStrategy->name,
            'recommended_ttl' => $analysis->recommendedTtl,
            'cacheability_score' => $analysis->cacheability->getScore(),
            'dependencies' => $analysis->dependencies,
            'potential_fragments' => $analysis->fragments,
            'optimization_suggestions' => $this->getOptimizationSuggestions($analysis),
        ];
    }

    public function warmupCache(array $templates): array
    {
        $results = [];

        foreach ($templates as $template => $contexts) {
            $results[$template] = [];

            foreach ($contexts as $context) {
                try {
                    $templateContext = new TemplateContext($template, $context);

                    // Warmup durch Rendering
                    $this->cacheManager->render($templateContext, function () {
                        return "<!-- Warmup content for {$template} -->";
                    });

                    $results[$template][] = 'success';
                } catch (\Exception $e) {
                    $results[$template][] = 'error: ' . $e->getMessage();
                }
            }
        }

        return $results;
    }

    public function healthCheck(): array
    {
        return [
            'cache_connection' => $this->testCacheConnection(),
            'template_analyzer' => $this->testTemplateAnalyzer(),
            'fragment_cache' => $this->testFragmentCache(),
            'strategy_availability' => $this->testStrategies(),
            'memory_usage' => $this->checkMemoryUsage(),
            'disk_space' => $this->checkDiskSpace(),
            'overall_status' => $this->determineOverallHealth(),
        ];
    }
}
