<?php

/**
 * Vala-IR helper function emitted after PHP-near activation/function code.
 */
final class ValaIrDeferredHelperFunction
{
    private int $startLine;
    private int $endLine;
    private array $comments;
    private string $name;
    private string $returnType;
    private array $params;
    private array $stmts;
    private string $stacktraceDisplayFrame;

    /**
     * Create a deferred helper function.
     *
     * Parameters are arrays with name and typeName keys.
     */
    public function __construct(int $startLine, int $endLine, array $comments, string $name, string $returnType, array $params, array $stmts, string $stacktraceDisplayFrame)
    {
        $this->startLine = $startLine;
        $this->endLine = $endLine;
        $this->comments = $comments;
        $this->name = $name;
        $this->returnType = $returnType;
        $this->params = $params;
        $this->stmts = $stmts;
        $this->stacktraceDisplayFrame = $stacktraceDisplayFrame;
    }

    /**
     * Convert to a plain array for debugging/export.
     */
    public function toArray(): array
    {
        return [
            'kind' => 'DeferredHelperFunction',
            'startLine' => $this->startLine,
            'endLine' => $this->endLine,
            'comments' => array_map(static fn (ValaIrComment $comment): array => $comment->toArray(), $this->comments),
            'name' => $this->name,
            'returnType' => $this->returnType,
            'params' => array_values(array_map(static function (array $param): array {
                return [
                    'name' => (string) ($param['name'] ?? ''),
                    'typeName' => (string) ($param['typeName'] ?? ''),
                ];
            }, $this->params)),
            'valaParams' => array_values(array_map(static function (array $param): array {
                return [
                    'name' => (string) ($param['name'] ?? ''),
                    'typeName' => (string) ($param['typeName'] ?? ''),
                ];
            }, $this->params)),
            'stmts' => array_map(
                static fn (object $stmt): array => method_exists($stmt, 'toArray') ? $stmt->toArray() : ['kind' => get_debug_type($stmt)],
                $this->stmts,
            ),
            'stacktraceDisplayFrame' => $this->stacktraceDisplayFrame,
        ];
    }
}
