<?php

namespace Datalumo\PhpSdk\DataObjects;

use Generator;
use IteratorAggregate;
use Traversable;

/**
 * @implements IteratorAggregate<int, StreamEvent>
 */
class StreamResponse implements IteratorAggregate
{
    /** @var Generator<int, StreamEvent> */
    private Generator $events;

    private ?array $headers;

    public function __construct(Generator $events, ?array $headers = null)
    {
        $this->events = $events;
        $this->headers = $headers;
    }

    public function getIterator(): Traversable
    {
        return $this->events;
    }

    /**
     * Iterate only over text delta events, yielding text chunks.
     *
     * @return Generator<int, string>
     */
    public function text(): Generator
    {
        foreach ($this->events as $event) {
            if ($event->isTextDelta() && $event->data !== null) {
                yield $event->data;
            }
        }
    }

    /**
     * Consume the entire stream and return the concatenated text.
     */
    public function fullText(): string
    {
        $text = '';

        foreach ($this->text() as $chunk) {
            $text .= $chunk;
        }

        return $text;
    }

    /**
     * Get the conversation ID from response headers (chat streams).
     */
    public function conversationId(): ?string
    {
        return $this->headers['X-Conversation-Id'][0] ?? $this->headers['x-conversation-id'][0] ?? null;
    }
}
