<?php

use Datalumo\PhpSdk\DataObjects\StreamEvent;
use Datalumo\PhpSdk\DataObjects\StreamResponse;

function createStreamResponse(array $events, ?array $headers = null): StreamResponse
{
    $generator = (function () use ($events) {
        foreach ($events as $event) {
            yield StreamEvent::fromArray($event);
        }
    })();

    return new StreamResponse($generator, $headers);
}

it('iterates over all events', function () {
    $response = createStreamResponse([
        ['type' => 'stream_start'],
        ['type' => 'text_delta', 'delta' => 'Hello'],
        ['type' => 'stream_end'],
    ]);

    $types = [];
    foreach ($response as $event) {
        $types[] = $event->type;
    }

    expect($types)->toBe(['stream_start', 'text_delta', 'stream_end']);
});

it('yields only text chunks via text()', function () {
    $response = createStreamResponse([
        ['type' => 'stream_start'],
        ['type' => 'text_delta', 'delta' => 'Hello '],
        ['type' => 'text_delta', 'delta' => 'world'],
        ['type' => 'citation', 'citation' => ['title' => 'Ref']],
        ['type' => 'stream_end'],
    ]);

    $chunks = iterator_to_array($response->text());

    expect($chunks)->toBe(['Hello ', 'world']);
});

it('concatenates full text', function () {
    $response = createStreamResponse([
        ['type' => 'text_delta', 'delta' => 'Hello '],
        ['type' => 'text_delta', 'delta' => 'world!'],
    ]);

    expect($response->fullText())->toBe('Hello world!');
});

it('returns empty string when no text deltas', function () {
    $response = createStreamResponse([
        ['type' => 'stream_start'],
        ['type' => 'stream_end'],
    ]);

    expect($response->fullText())->toBe('');
});

it('extracts conversation id from headers', function () {
    $response = createStreamResponse([], [
        'X-Conversation-Id' => ['conv-123'],
    ]);

    expect($response->conversationId())->toBe('conv-123');
});

it('extracts conversation id from lowercase headers', function () {
    $response = createStreamResponse([], [
        'x-conversation-id' => ['conv-456'],
    ]);

    expect($response->conversationId())->toBe('conv-456');
});

it('returns null conversation id when header missing', function () {
    $response = createStreamResponse([], []);

    expect($response->conversationId())->toBeNull();
});
