<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Validation;

use PpPhp\Core\Platform\Workflow\WorkflowActivity;
use PpPhp\Core\Platform\Workflow\WorkflowDefinition;
use PpPhp\Core\Platform\Workflow\WorkflowRuntime;

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

        $definition = $runtime->register(WorkflowDefinition::create('onboarding_workflow', 'Onboarding Workflow', [
            WorkflowActivity::create('collect_data', 'Collect Data', 'system')->toArray(),
            WorkflowActivity::create('manager_approval', 'Manager Approval', 'human', ['assignee' => 'manager'])->toArray(),
            WorkflowActivity::create('activate_account', 'Activate Account', 'system')->toArray(),
        ], [
            ['from' => 'collect_data', 'to' => 'manager_approval'],
            ['from' => 'manager_approval', 'to' => 'activate_account'],
        ]));

        $instance = $runtime->start('onboarding_workflow', ['userId' => 'workflow-user-1']);
        $firstRun = $instance ? $runtime->run($instance->instanceId()) : 0;

        $summaryAfterHumanStop = $runtime->summary();
        $taskId = '';
        foreach ($summaryAfterHumanStop['tasks'] as $task) {
            if (($task['activityId'] ?? '') === 'manager_approval') {
                $taskId = (string) ($task['taskId'] ?? '');
            }
        }

        $completedTask = $taskId !== '' && $runtime->completeTask($taskId);
        $summaryAfterTask = $runtime->summary();
        $instanceId = (string) ($summaryAfterTask['instances'][0]['instanceId'] ?? '');
        $secondRun = $instanceId !== '' ? $runtime->run($instanceId) : 0;

        $runtime->save();

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

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

        $checks = [
            'definition' => $definition->workflowId() === 'onboarding_workflow',
            'start' => $instance !== null,
            'systemRun' => $firstRun === 1,
            'humanTask' => $taskId !== '' && $completedTask,
            'completion' => ($stats['completed'] ?? 0) === 1 && $secondRun === 1,
            'statistics' => ($stats['workflows'] ?? 0) === 1 && ($stats['executions'] ?? 0) === 3,
            'persistence' => $second->store()->exists(),
            'hydration' => count($summary['instances']) === 1,
        ];

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

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