<?php

/**
 * PHP-IR try/catch statement for one typed catch arm.
 */
final class PhpIrTryCatch
{
    private int $startLine;
    private int $endLine;
    private array $comments;
    private array $tryStmts;
    private array $catchArms;

    /**
     * Create a try/catch statement.
     *
     * @param int $startLine Source start line.
     * @param int $endLine Source end line.
     * @param array $comments PHP comments attached to the try statement.
     * @param array $tryStmts Statements in the try block.
     * @param array $catchArms Catch arms; each has className, varName and stmts.
     */
    public function __construct(int $startLine, int $endLine, array $comments, array $tryStmts, array $catchArms)
    {
        $this->startLine = $startLine;
        $this->endLine = $endLine;
        $this->comments = $comments;
        $this->tryStmts = $tryStmts;
        $this->catchArms = $catchArms;
    }

    /** Convert to a plain array for debugging/export. */
    public function toArray(): array
    {
        return [
            'kind' => 'TryCatch',
            'startLine' => $this->startLine,
            'endLine' => $this->endLine,
            'comments' => array_map(static fn (PhpIrComment $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),
            'catchArms' => array_map(static fn (array $arm): array => [
                'className' => (string) ($arm['className'] ?? 'Exception'),
                'varName' => (string) ($arm['varName'] ?? 'e'),
                'stmts' => array_map(static fn (object $stmt): array => method_exists($stmt, 'toArray') ? $stmt->toArray() : ['kind' => get_debug_type($stmt)], $arm['stmts'] ?? []),
            ], $this->catchArms),
        ];
    }
}
