<?php
namespace boru\ai\Tests\Provider\Gemini;

use boru\ai\Http\HttpResponse;
use boru\ai\Provider\Gemini\GeminiClient;
use boru\ai\Provider\Gemini\GeminiMapper;
use boru\ai\Provider\Gemini\GeminiProvider;
use boru\ai\Schema\Request;
use boru\ai\Stream\StreamEvent;
use boru\ai\Tests\Fakes\FakeHttpClient;
use PHPUnit\Framework\TestCase;

class GeminiProviderStreamingTest extends TestCase
{
    public function testExecuteStreamsNormalizedEventsAndReturnsFinalResponse()
    {
        $httpClient = new FakeHttpClient();
        $httpResponse = new HttpResponse();
        $httpResponse->statusCode(200);
        $httpClient->queueStream(array(
            "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"Hello \"}]}}]}\n\n",
            "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"world\"}]},\"finishReason\":\"STOP\"}],\"modelVersion\":\"gemini-2.5-pro\",\"responseId\":\"resp_1\"}\n\n",
        ), $httpResponse);

        $client = new GeminiClient('test-key', array(), $httpClient);
        $provider = new GeminiProvider($client, new GeminiMapper());

        $request = new Request();
        $request->model('gemini-2.5-pro')->addMessage('Hello')->option('stream', true);

        $events = array();
        $response = $provider->execute($request, function ($event) use (&$events) {
            $events[] = $event;
        });

        $this->assertSame('Hello world', $response->text());
        $this->assertGreaterThanOrEqual(3, count($events));
        $this->assertSame(StreamEvent::TEXT_DELTA, $events[0]->type());
        $this->assertSame('Hello ', $events[0]->delta());
        $this->assertSame('text/event-stream', $httpClient->requests[0]->header('Accept'));
    }
}
