<?php
declare(strict_types=1);

namespace PpPhp\Core\Assets\Validation;

use PpPhp\Core\Assets\AssetRuntime;
use PpPhp\Core\Assets\AssetRegistry;
use PpPhp\Core\Resources\ResourceRegistry;

final class AssetRuntimeVerifier
{
    public function verify(): array
    {
        ResourceRegistry::reset();
        AssetRegistry::reset();

        $runtime = new AssetRuntime();
        $registered = $runtime->registerAllIntoAssetRegistry();
        $stats = $runtime->stats();
        $manifest = $runtime->manifest(['inter-font', 'designer-base-theme', 'bootstrap-icons', 'chartjs'], 'verify_assets');
        $enabled = $runtime->enable('designer-base-theme');
        $head = $runtime->renderPackageHead(['inter-font', 'designer-base-theme', 'bootstrap-icons']);
        $footer = $runtime->renderPackageFooter(['chartjs', 'sortablejs']);
        $generated = $runtime->packageForGeneratedApp(['inter-font', 'designer-base-theme', 'chartjs'], 'demo_app');

        $checks = [
            'resourceScan' => ($stats['packages'] ?? 0) >= 9,
            'registerPackages' => $registered >= 9 && AssetRegistry::has('designer-base-theme'),
            'manifest' => ($manifest['summary']['packages'] ?? 0) >= 3 && ($manifest['summary']['assets'] ?? 0) >= 3,
            'enable' => $enabled === true && in_array('designer-base-theme', AssetRegistry::enabled(), true),
            'headRender' => str_contains($head, '<link') && str_contains($head, 'stylesheet'),
            'footerRender' => str_contains($footer, '<script'),
            'generatedApp' => ($generated['appId'] ?? '') === 'demo_app' && count($generated['copyPlan'] ?? []) >= 2,
            'statistics' => ($stats['css'] ?? 0) >= 1 && ($stats['js'] ?? 0) >= 1 && ($stats['images'] ?? 0) >= 1,
        ];

        $issues = [];
        foreach ($checks as $check => $ok) {
            if (!$ok) {
                $issues[] = ['check' => $check, 'message' => 'Asset runtime verification failed: ' . $check];
            }
        }

        return [
            'ok' => !in_array(false, $checks, true),
            'checks' => $checks,
            'issues' => $issues,
            'summary' => array_replace($stats, [
                'checks' => count($checks),
                'passed' => count(array_filter($checks)),
                'failed' => count($checks) - count(array_filter($checks)),
                'registered' => $registered,
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ]),
            'manifest' => $manifest,
        ];
    }
}
