<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Sourcing\Saga;

use PpPhp\Core\Platform\Event\Sourcing\Command\CommandBusRuntime;
use PpPhp\Core\Platform\Event\Sourcing\Command\CommandMessage;
use PpPhp\Core\Platform\Event\Sourcing\Domain\DomainEventEnvelope;

final class SagaRuntime
{
    private static ?self $instance = null;

    private SagaRegistry $registry;
    /** @var array<string, SagaInstance> */
    private array $instances = [];
    /** @var SagaExecutionResult[] */
    private array $executions = [];
    private SagaStore $store;

    private function __construct(private readonly string $basePath)
    {
        $this->registry = new SagaRegistry();
        $this->store = new SagaStore($basePath);
        $this->hydrate();
    }

    public static function instance(?string $basePath = null): self
    {
        if (self::$instance === null) {
            $basePath ??= self::detectBasePath();
            self::$instance = new self($basePath);
        }

        return self::$instance;
    }

    public static function resetInstance(?string $basePath = null): self
    {
        $basePath ??= self::detectBasePath();
        self::$instance = new self($basePath);

        return self::$instance;
    }

    public function register(SagaDefinition $definition): SagaDefinition
    {
        $this->registry->register($definition);
        $this->save();
        return $definition;
    }

    public function startFromEvent(DomainEventEnvelope $event): array
    {
        $started = [];

        foreach ($this->registry->startersFor($event->eventType()) as $definition) {
            $instance = SagaInstance::start($definition, $event->aggregateType() . ':' . $event->eventId(), [
                'eventId' => $event->eventId(),
                'eventType' => $event->eventType(),
                'sequence' => $event->sequence(),
            ]);
            $this->instances[$instance->instanceId()] = $instance;
            $started[] = $instance;
        }

        $this->save();
        return $started;
    }

    public function run(string $instanceId): int
    {
        $instance = $this->instances[$instanceId] ?? null;
        if ($instance === null || $instance->completed() || $instance->status() === 'failed') {
            return 0;
        }

        $definition = $this->registry->get($instance->sagaId());
        if ($definition === null) {
            return 0;
        }

        $steps = array_map(static fn (array $step): SagaStep => SagaStep::fromArray($step), $definition->steps());
        $executed = 0;

        while (!$instance->completed() && isset($steps[$instance->currentStep()])) {
            $step = $steps[$instance->currentStep()];

            $command = CommandMessage::create(
                $step->commandType(),
                $instance->correlationId() . ':' . $step->stepId(),
                $step->aggregateType(),
                $step->payload(),
                ['sagaId' => $instance->sagaId(), 'instanceId' => $instance->instanceId(), 'stepId' => $step->stepId()]
            );

            $result = CommandBusRuntime::instance($this->basePath)->dispatch($command);

            if (!$result->successful()) {
                $this->executions[] = SagaExecutionResult::failed($instance, $step, 'command dispatch failed');
                $instance = $instance->fail('command dispatch failed');
                $this->instances[$instance->instanceId()] = $instance;
                $this->save();
                return $executed;
            }

            $this->executions[] = SagaExecutionResult::success($instance, $step);
            $instance = $instance->advance($step->stepId(), count($steps));
            $this->instances[$instance->instanceId()] = $instance;
            $executed++;
        }

        $this->save();
        return $executed;
    }

    public function hydrate(): void
    {
        $snapshot = $this->store->load();

        if ($snapshot->definitions() !== []) {
            $this->registry = SagaRegistry::fromArray($snapshot->definitions());
        }

        $this->instances = [];
        foreach ($snapshot->instances() as $instance) {
            if (is_array($instance)) {
                $i = SagaInstance::fromArray($instance);
                $this->instances[$i->instanceId()] = $i;
            }
        }

        $this->executions = [];
        foreach ($snapshot->executions() as $execution) {
            if (is_array($execution)) {
                $this->executions[] = SagaExecutionResult::fromArray($execution);
            }
        }
    }

    public function snapshot(): SagaRuntimeSnapshot
    {
        $definitions = $this->registry->toArray();
        $instances = array_map(static fn (SagaInstance $instance): array => $instance->toArray(), array_values($this->instances));
        $executions = array_map(static fn (SagaExecutionResult $execution): array => $execution->toArray(), $this->executions);

        return new SagaRuntimeSnapshot(
            $definitions,
            $instances,
            $executions,
            SagaStatistics::from($definitions, $instances, $executions),
            date('c')
        );
    }

    public function save(): SagaRuntimeSnapshot
    {
        return $this->store->save($this->snapshot());
    }

    public function clear(): void
    {
        $this->registry = new SagaRegistry();
        $this->instances = [];
        $this->executions = [];
        $this->store->reset();
    }

    public function store(): SagaStore { return $this->store; }

    public function summary(): array
    {
        $snapshot = $this->snapshot();

        return [
            'definitions' => $snapshot->definitions(),
            'instances' => $snapshot->instances(),
            'executions' => $snapshot->executions(),
            'statistics' => $snapshot->statistics(),
            'persisted' => $this->store->exists(),
            'stateFile' => $this->store->stateFile(),
        ];
    }

    private static function detectBasePath(): string
    {
        $candidate = dirname(__DIR__, 5);
        $real = realpath($candidate);
        return $real !== false ? $real : $candidate;
    }
}
