<?php

declare(strict_types=1);

namespace Drupal\flowdrop_runtime\Event;

use Symfony\Contracts\EventDispatcher\Event;

/**
 * Event dispatched after a pipeline run finishes executing.
 *
 * Fired for 'completed', 'failed', and 'paused' outcomes. Subscribers can use
 * this to record per-run status without waiting for the session-level result.
 * Dispatched by StateGraphOrchestrator after the final status is determined.
 *
 * @internal
 */
class PipelineCompletedEvent extends Event {

  /**
   * The event name.
   */
  public const string NAME = 'flowdrop_runtime.pipeline.completed';

  /**
   * Playground context extracted from the pipeline execution context, or NULL.
   */
  private readonly ?PlaygroundContext $playgroundContext;

  /**
   * Constructs a new PipelineCompletedEvent.
   *
   * @param array<string, mixed> $pipelineContext
   *   The pipeline execution context (from
   *   FlowDropPipelineRuntimeInterface::getExecutionContext()).
   * @param string $executionId
   *   The execution ID for this pipeline run.
   * @param string $status
   *   One of 'completed', 'failed', or 'paused'.
   * @param int $executionTimeUs
   *   Total wall-clock execution time in microseconds.
   * @param string|null $pipelineId
   *   The pipeline entity ID, when the run is backed by a pipeline entity.
   *   Distinct from $executionId, which for stategraph runs carries the
   *   checkpoint thread ID, not the entity ID.
   */
  public function __construct(
    private readonly array $pipelineContext,
    private readonly string $executionId,
    private readonly string $status,
    private readonly int $executionTimeUs,
    private readonly ?string $pipelineId = NULL,
  ) {
    $this->playgroundContext = PlaygroundContext::fromPipelineContext($pipelineContext);
  }

  /**
   * Returns the playground context, or NULL when not running in a playground.
   */
  public function getPlaygroundContext(): ?PlaygroundContext {
    return $this->playgroundContext;
  }

  /**
   * Returns the execution ID for this pipeline run.
   */
  public function getExecutionId(): string {
    return $this->executionId;
  }

  /**
   * Returns the final pipeline status: 'completed', 'failed', or 'paused'.
   */
  public function getStatus(): string {
    return $this->status;
  }

  /**
   * Returns the total wall-clock execution time in microseconds.
   */
  public function getExecutionTimeUs(): int {
    return $this->executionTimeUs;
  }

  /**
   * Returns the raw pipeline execution context the run ended with.
   *
   * @return array<string, mixed>
   *   The pipeline execution context.
   */
  public function getPipelineContext(): array {
    return $this->pipelineContext;
  }

  /**
   * Returns the pipeline entity ID, or NULL for non-entity-backed runs.
   */
  public function getPipelineId(): ?string {
    return $this->pipelineId;
  }

}
