<?php

namespace boru\boruai\Openai\Stream\Listener;

use boru\boruai\Openai\Stream\AbstractStreamEventListener;
use boru\boruai\Openai\Stream\StreamEvent;

class ReasoningTextListener extends AbstractStreamEventListener
{
    /** @var string */
    private $buffer = '';

    /** @var bool */
    private $done = false;

    public function handle(StreamEvent $event)
    {
        $type = $event->type();

        if ($type === StreamEvent::RESPONSE_REASONING_TEXT_DELTA) {
            $delta = method_exists($event, 'delta') ? $event->delta() : null;
            if (is_string($delta)) {
                $this->buffer .= $delta;
            }
            return true;
        }

        if ($type === StreamEvent::RESPONSE_REASONING_TEXT_DONE) {
            $method = "text"; // Using method variable to avoid IDE warnings.
            if (method_exists($event, $method)) {
                $text = $event->$method();
                if (is_string($text) && $text !== '') {
                    $this->buffer = $text;
                }
            }
            $this->done = true;
            return true;
        }

        return false;
    }

    public function getText()
    {
        return $this->buffer;
    }

    public function isDone()
    {
        return $this->done ? true : false;
    }
}
