<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Engine\Validation;

use PpPhp\Core\Platform\Workflow\Engine\WorkflowEngineDefinition;
use PpPhp\Core\Platform\Workflow\Engine\WorkflowEngineRuntime;
use PpPhp\Core\Platform\Workflow\Engine\WorkflowGateway;

final class WorkflowEngineVerifier
{
    public function verify(string $basePath): array
    {
        $runtime = WorkflowEngineRuntime::resetInstance($basePath);
        $runtime->clear();

        $definition = $runtime->register(WorkflowEngineDefinition::create(
            'approval_engine_workflow',
            'Approval Engine Workflow',
            [
                ['activityId' => 'submit', 'type' => 'activity'],
                ['activityId' => 'manager_review', 'type' => 'activity'],
                ['activityId' => 'finance_review', 'type' => 'activity'],
                ['activityId' => 'finalize', 'type' => 'activity'],
            ],
            [
                WorkflowGateway::parallel('parallel_review', ['manager_review', 'finance_review'], 'finalize')->toArray(),
            ],
            [
                ['from' => 'submit', 'to' => 'parallel_review'],
                ['from' => 'manager_review', 'to' => 'finalize'],
                ['from' => 'finance_review', 'to' => 'finalize'],
            ],
            'submit'
        ));

        $state = $runtime->start('approval_engine_workflow', ['amount' => 500]);
        $afterSubmit = $state ? $runtime->complete($state->instanceId(), 'submit') : null;

        $parallelActive = $afterSubmit !== null
            && in_array('manager_review', $afterSubmit->activeActivities(), true)
            && in_array('finance_review', $afterSubmit->activeActivities(), true);

        if ($state !== null) {
            $runtime->complete($state->instanceId(), 'manager_review');
            $runtime->complete($state->instanceId(), 'finance_review');
            $runtime->complete($state->instanceId(), 'finalize');
        }

        $runtime->save();

        $second = WorkflowEngineRuntime::resetInstance($basePath);
        $second->hydrate();

        $summary = $second->summary();
        $stats = $summary['statistics'];

        $checks = [
            'definition' => $definition->workflowId() === 'approval_engine_workflow',
            'start' => $state !== null,
            'parallelGateway' => $parallelActive,
            'stateMachine' => ($stats['completed'] ?? 0) === 1,
            'results' => ($stats['successfulResults'] ?? 0) >= 4,
            'statistics' => ($stats['definitions'] ?? 0) === 1 && ($stats['states'] ?? 0) === 1,
            'persistence' => $second->store()->exists(),
            'hydration' => count($summary['states']) === 1,
        ];

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

        return [
            'ok' => !in_array(false, $checks, true),
            'checks' => $checks,
            'issues' => $issues,
            'summary' => [
                'definitions' => $stats['definitions'] ?? 0,
                'states' => $stats['states'] ?? 0,
                'completed' => $stats['completed'] ?? 0,
                'results' => $stats['results'] ?? 0,
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
        ];
    }
}
