<?php

declare(strict_types=1);

namespace PpPhp\Core\Designer\Selection;

use PpPhp\Core\Designer\Templates\MinimalListPageTemplate;

final class DesignerSelectionVerifier
{
    public function verify(): array
    {
        $page = (new MinimalListPageTemplate())->make('customers', [
            ['name' => 'id', 'label' => 'ID'],
            ['name' => 'first_name', 'label' => 'First Name'],
            ['name' => 'email', 'label' => 'Email'],
        ]);

        $runtime = new DesignerSelectionRuntime();
        $tree = $runtime->tree($page);
        $columnTarget = $runtime->findTarget($tree, 'data_grid_main:column:first_name');
        $actionTarget = $runtime->findTarget($tree, 'data_grid_main:action_button:edit_btn');
        $inspector = $columnTarget ? $runtime->inspect($page, $columnTarget) : [];

        $checks = [
            'factoryCollisionFixed' => method_exists(DesignerSelectionTarget::class, 'partTarget'),
            'tree' => ($tree['type'] ?? '') === 'page' && count((array) ($tree['children'] ?? [])) === 3,
            'componentTargets' => $runtime->findTarget($tree, 'data_grid_main') !== null,
            'partTargets' => $columnTarget !== null && $actionTarget !== null,
            'breadcrumb' => count((array) ($inspector['breadcrumb'] ?? [])) >= 3,
            'inspectorTabs' => count((array) ($inspector['tabs'] ?? [])) >= 8,
            'actions' => in_array('duplicate', (array) ($inspector['actions'] ?? []), true),
        ];

        $issues = [];
        foreach ($checks as $check => $ok) {
            if (!$ok) {
                $issues[] = ['check' => $check, 'message' => 'Designer selection 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)),
                'treeNodes' => $this->countNodes($tree),
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
            'tree' => $tree,
            'inspector' => $inspector,
        ];
    }

    private function countNodes(array $node): int
    {
        $count = 1;
        foreach ((array) ($node['children'] ?? []) as $child) {
            if (is_array($child)) {
                $count += $this->countNodes($child);
            }
        }
        return $count;
    }
}
