<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\Toolbox\Validation;

use PpPhp\Core\Designer\Toolbox\DesignerToolboxRuntime;

final class DesignerToolboxVerifier
{
    public function verify(): array
    {
        $runtime = new DesignerToolboxRuntime();

        $state = [
            'favorites' => ['button', 'data_grid'],
            'recent' => ['input', 'button', 'card'],
        ];

        $toolbox = $runtime->build($state);
        $search = $runtime->build(array_replace($state, ['query' => 'grid']));
        $favorites = $runtime->favorites($state);
        $recent = $runtime->recent($state);
        $plugins = $runtime->pluginDiscovery([
            ['type' => 'custom_chart', 'title' => 'Custom Chart', 'plugin' => 'analytics'],
            ['type' => '', 'title' => 'Broken Plugin'],
        ]);

        $dragPayloadOk = false;
        foreach ((array) ($toolbox['groups'] ?? []) as $group) {
            foreach ((array) ($group['items'] ?? []) as $item) {
                if (($item['drag']['mime'] ?? '') === 'application/x-ppphp-component'
                    && (($item['drag']['payload']['source'] ?? '') === 'toolbox')
                    && (($item['drag']['payload']['type'] ?? '') !== '')
                ) {
                    $dragPayloadOk = true;
                    break 2;
                }
            }
        }

        $checks = [
            'groups' => ($toolbox['summary']['groups'] ?? 0) >= 9,
            'items' => ($toolbox['summary']['items'] ?? 0) >= 18,
            'search' => ($search['summary']['items'] ?? 0) >= 1 && str_contains(json_encode($search), 'data_grid'),
            'favorites' => count($favorites) === 2,
            'recent' => count($recent) === 3,
            'dragPayload' => $dragPayloadOk,
            'pluginDiscovery' => ($plugins['valid'] ?? 0) === 1 && ($plugins['invalid'] ?? 0) === 1,
        ];

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

        return [
            'ok' => !in_array(false, $checks, true),
            'checks' => $checks,
            'issues' => $issues,
            'summary' => [
                'checks' => count($checks),
                'passed' => count(array_filter($checks)),
                'failed' => count($checks) - count(array_filter($checks)),
                'groups' => $toolbox['summary']['groups'] ?? 0,
                'items' => $toolbox['summary']['items'] ?? 0,
                'favorites' => count($favorites),
                'recent' => count($recent),
                'plugins' => count($plugins['plugins'] ?? []),
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
        ];
    }
}
