<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Workflow\Bpmn\BpmnRuntime;

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

        $xml = '<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" id="Definitions_verify" targetNamespace="https://ppphp.local/workflow/bpmn">
  <bpmn:process id="bpmn_verify_process" name="BPMN Verify Process" isExecutable="true">
    <bpmn:startEvent id="start" name="Start"/>
    <bpmn:userTask id="approve" name="Approve"/>
    <bpmn:exclusiveGateway id="decision" name="Decision"/>
    <bpmn:serviceTask id="notify" name="Notify"/>
    <bpmn:endEvent id="end" name="End"/>
    <bpmn:sequenceFlow id="flow_1" sourceRef="start" targetRef="approve"/>
    <bpmn:sequenceFlow id="flow_2" sourceRef="approve" targetRef="decision"/>
    <bpmn:sequenceFlow id="flow_3" sourceRef="decision" targetRef="notify"/>
    <bpmn:sequenceFlow id="flow_4" sourceRef="notify" targetRef="end"/>
  </bpmn:process>
</bpmn:definitions>';

        $model = $runtime->importXml($xml);
        $exported = $runtime->exportXml($model->processId());
        $compiled = $runtime->compile($model->processId());
        $runtime->save();

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

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

        $checks = [
            'import' => $model->processId() === 'bpmn_verify_process' && count($model->elements()) === 5,
            'export' => str_contains($exported, 'bpmn:process') && str_contains($exported, 'bpmn_verify_process'),
            'compile' => $compiled !== null && $compiled->workflowId() === 'bpmn_verify_process',
            'designer' => count($summary['designerModels']) === 1,
            'statistics' => ($stats['models'] ?? 0) === 1 && ($stats['imports'] ?? 0) === 1 && ($stats['exports'] ?? 0) === 1,
            'persistence' => $second->store()->exists(),
            'hydration' => count($summary['models']) === 1,
        ];

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

        return [
            'ok' => !in_array(false, $checks, true),
            'checks' => $checks,
            'issues' => $issues,
            'summary' => [
                'models' => $stats['models'] ?? 0,
                'designerModels' => $stats['designerModels'] ?? 0,
                'imports' => $stats['imports'] ?? 0,
                'exports' => $stats['exports'] ?? 0,
                'elements' => $stats['elements'] ?? 0,
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
        ];
    }
}
