<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Workflow\HumanTask\HumanTaskRecord;
use PpPhp\Core\Platform\Workflow\HumanTask\HumanTaskRuntime;

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

        $task = $runtime->createTask(HumanTaskRecord::create(
            'workflow-inst-human-1',
            'manager_approval',
            'Manager Approval',
            '',
            ['alice'],
            ['managers'],
            ['amount' => 500],
            'high'
        ));

        $aliceInbox = $runtime->inbox('alice', []);
        $claim = $runtime->claim($task->taskId(), 'alice');
        $complete = $runtime->complete($task->taskId(), ['approved' => true]);

        $runtime->createTask(HumanTaskRecord::create(
            'workflow-inst-human-2',
            'finance_review',
            'Finance Review',
            'bob',
            [],
            [],
            ['amount' => 900],
            'normal'
        ));

        $bobInbox = $runtime->inbox('bob', []);

        $runtime->save();

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

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

        $checks = [
            'create' => $task->taskId() !== '',
            'inbox' => count($aliceInbox) === 1 && count($bobInbox) === 1,
            'claim' => $claim === true,
            'complete' => $complete === true,
            'assignment' => ($stats['successfulAssignments'] ?? 0) === 1,
            'statistics' => ($stats['tasks'] ?? 0) === 2 && ($stats['completed'] ?? 0) === 1 && ($stats['assigned'] ?? 0) === 1,
            'persistence' => $second->store()->exists(),
            'hydration' => count($summary['tasks']) === 2,
        ];

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

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