<?php

/**
 * Vala-IR statement for runtime dispatch of a dynamic PHP include path.
 */
final class ValaIrDynamicIncludeDispatchStatement
{
    private int $startLine;
    private int $endLine;
    private array $comments;
    private object $pathExpr;
    private array $entries;
    private string $pathVariable;
    private array $failureStmts;

    /**
     * Create a dynamic include dispatcher statement.
     *
     * Each entry contains IR-created match data:
     * - exactPaths: strings compared with ==
     * - suffixPaths: strings passed to has_suffix()
     * - registerCallee: source-set registration helper
     * - mainCallee: source-set activation helper
     *
     * `$failureStmts` is the IR-created else branch, normally a runtime
     * throw_exception(...) call for the include failure.
     */
    public function __construct(int $startLine, int $endLine, array $comments, object $pathExpr, array $entries, string $pathVariable = '__phpefc_include_path', array $failureStmts = [])
    {
        $this->startLine = $startLine;
        $this->endLine = $endLine;
        $this->comments = $comments;
        $this->pathExpr = $pathExpr;
        $this->entries = $entries;
        $this->pathVariable = $pathVariable;
        $this->failureStmts = $failureStmts;
    }

    /**
     * Convert to a plain array for debugging/export.
     */
    public function toArray(): array
    {
        return [
            'kind' => 'DynamicIncludeDispatchStatement',
            'startLine' => $this->startLine,
            'endLine' => $this->endLine,
            'comments' => array_map(static fn (ValaIrComment $comment): array => $comment->toArray(), $this->comments),
            'pathVariable' => $this->pathVariable,
            'pathExpr' => method_exists($this->pathExpr, 'toArray') ? $this->pathExpr->toArray() : ['kind' => get_debug_type($this->pathExpr)],
            'entries' => array_values(array_map(static function (array $entry): array {
                return [
                    'sourcePath' => (string) ($entry['sourcePath'] ?? ''),
                    'exactPaths' => array_values(array_map(static fn (string $path): string => $path, is_array($entry['exactPaths'] ?? null) ? $entry['exactPaths'] : [])),
                    'suffixPaths' => array_values(array_map(static fn (string $path): string => $path, is_array($entry['suffixPaths'] ?? null) ? $entry['suffixPaths'] : [])),
                    'registerCallee' => (string) ($entry['registerCallee'] ?? ''),
                    'mainCallee' => (string) ($entry['mainCallee'] ?? ''),
                ];
            }, $this->entries)),
            'failureStmts' => array_map(
                static fn (object $stmt): array => method_exists($stmt, 'toArray') ? $stmt->toArray() : ['kind' => get_debug_type($stmt)],
                $this->failureStmts,
            ),
        ];
    }
}
