<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\Shell\Validation;

use PpPhp\Core\Designer\Shell\DesignerApplicationShellRuntime;

final class DesignerApplicationShellVerifier
{
    public function verify(): array
    {
        $runtime = new DesignerApplicationShellRuntime();
        $shell = $runtime->createCrudApplication('crm_app', 'CRM Application', [
            'customers' => [
                ['name' => 'id', 'type' => 'number'],
                ['name' => 'name', 'type' => 'text'],
                ['name' => 'email', 'type' => 'email'],
            ],
            'orders' => [
                ['name' => 'id', 'type' => 'number'],
                ['name' => 'customer', 'type' => 'text'],
                ['name' => 'total', 'type' => 'currency'],
            ],
        ]);
        $html = $runtime->render($shell);
        $validation = $runtime->validate($shell);
        $stats = $runtime->stats();

        $checks = [
            'shell' => ($shell['type'] ?? '') === 'application_shell',
            'dashboard' => (($shell['dashboard']['pageType'] ?? '') === 'dashboard'),
            'navigation' => (($shell['navigation']['type'] ?? '') === 'navigation_menu'),
            'pages' => ($validation['pages'] ?? 0) >= 9,
            'authPages' => ($validation['authPages'] ?? 0) === 8,
            'routes' => ($validation['routes'] ?? 0) >= 17,
            'assets' => ($validation['assets'] ?? 0) >= 4,
            'renderer' => str_contains($html, 'ppd-application-shell'),
            'validation' => ($validation['ok'] ?? false) === true,
            'operations' => ($stats['operations'] ?? 0) >= 1,
        ];

        $issues = [];
        foreach ($checks as $check => $ok) {
            if (!$ok) {
                $issues[] = ['check' => $check, 'message' => 'Designer application shell 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)),
                'pages' => $validation['pages'] ?? 0,
                'authPages' => $validation['authPages'] ?? 0,
                'routes' => $validation['routes'] ?? 0,
                'assets' => $validation['assets'] ?? 0,
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ]),
        ];
    }
}
