<?php

/**
 * Vala-IR statement for while-loop control flow.
 */
final class ValaIrWhileStatement
{
    private int $startLine;
    private int $endLine;
    private array $comments;
    private object $condition;
    private array $stmts;

    /**
     * Create a while-loop statement.
     *
     * @param int $startLine Original PHP start line.
     * @param int $endLine Original PHP end line.
     * @param array $comments Vala-IR comments attached to the loop.
     * @param object $condition Vala bool expression.
     * @param array $stmts Vala-IR body statements.
     */
    public function __construct(int $startLine, int $endLine, array $comments, object $condition, array $stmts)
    {
        $this->startLine = $startLine;
        $this->endLine = $endLine;
        $this->comments = $comments;
        $this->condition = $condition;
        $this->stmts = $stmts;
    }

    /** Return body statements for optimizer passes. */
    public function stmts(): array
    {
        return $this->stmts;
    }

    /** Return a copy with updated body statements. */
    public function withStmts(array $stmts): self
    {
        return new self($this->startLine, $this->endLine, $this->comments, $this->condition, $stmts);
    }

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