<?php

/**
 * Vala-IR try/catch statement for catching PHPEF runtime errors.
 */
final class ValaIrTryCatchStatement
{
    private int $startLine;
    private int $endLine;
    private array $comments;
    private array $tryStmts;
    private string $catchType;
    private string $catchName;
    private array $catchStmts;

    /**
     * Create a try/catch statement.
     *
     * @param int $startLine Source start line.
     * @param int $endLine Source end line.
     * @param array $comments Vala-IR comments attached to the try statement.
     * @param array $tryStmts Statements in the try block.
     * @param string $catchType Host catch type, usually Error.
     * @param string $catchName Host catch variable name.
     * @param array $catchStmts Already-lowered statements in the host catch block.
     */
    public function __construct(int $startLine, int $endLine, array $comments, array $tryStmts, string $catchType, string $catchName, array $catchStmts)
    {
        $this->startLine = $startLine;
        $this->endLine = $endLine;
        $this->comments = $comments;
        $this->tryStmts = $tryStmts;
        $this->catchType = $catchType;
        $this->catchName = $catchName;
        $this->catchStmts = $catchStmts;
    }

    /** Convert to a plain array for debugging/export. */
    public function toArray(): array
    {
        return [
            'kind' => 'TryCatchStatement',
            'startLine' => $this->startLine,
            'endLine' => $this->endLine,
            'comments' => array_map(static fn (ValaIrComment $comment): array => $comment->toArray(), $this->comments),
            'tryStmts' => array_map(static fn (object $stmt): array => method_exists($stmt, 'toArray') ? $stmt->toArray() : ['kind' => get_debug_type($stmt)], $this->tryStmts),
            'catchType' => $this->catchType,
            'catchName' => $this->catchName,
            'catchStmts' => array_map(static fn (object $stmt): array => method_exists($stmt, 'toArray') ? $stmt->toArray() : ['kind' => get_debug_type($stmt)], $this->catchStmts),
        ];
    }
}
