<?php

declare(strict_types=1);

namespace Tests\Providers\Gemini;

use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Prism\Prism\Enums\FinishReason;
use Prism\Prism\Enums\Provider;
use Prism\Prism\Exceptions\PrismException;
use Prism\Prism\Prism;
use Prism\Prism\Providers\Gemini\ValueObjects\MessagePartWithSearchGroundings;
use Prism\Prism\Providers\Gemini\ValueObjects\SearchGrounding;
use Prism\Prism\Tool;
use Prism\Prism\ValueObjects\Messages\Support\Document;
use Prism\Prism\ValueObjects\Messages\Support\Image;
use Prism\Prism\ValueObjects\Messages\SystemMessage;
use Prism\Prism\ValueObjects\Messages\UserMessage;
use Tests\Fixtures\FixtureResponse;

beforeEach(function (): void {
    config()->set('prism.providers.gemini.api_key', env('GEMINI_API_KEY', 'sss-1234567890'));
});

describe('Text generation for Gemini', function (): void {
    it('can generate text with a prompt', function (): void {
        FixtureResponse::fakeResponseSequence('*', 'gemini/generate-text-with-a-prompt');

        $response = Prism::text()
            ->using(Provider::Gemini, 'gemini-1.5-flash')
            ->withPrompt('Who are you?')
            ->withMaxTokens(10)
            ->generate();

        expect($response->text)->toBe(
            "I am a large language model, trained by Google.  I am an AI, and I don't have a name, feelings, or personal experiences.  My purpose is to process information and respond to a wide range of prompts and questions in a helpful and informative way.\n"
        )
            ->and($response->usage->promptTokens)->toBe(4)
            ->and($response->usage->completionTokens)->toBe(57)
            ->and($response->meta->id)->toBe('')
            ->and($response->meta->model)->toBe('gemini-1.5-flash')
            ->and($response->finishReason)->toBe(FinishReason::Stop);
    });

    it('can generate text with a system prompt', function (): void {
        FixtureResponse::fakeResponseSequence('*', 'gemini/generate-text-with-system-prompt');

        $response = Prism::text()
            ->using(Provider::Gemini, 'gemini-1.5-flash')
            ->withSystemPrompt('You are a helpful AI assistant named Prism generated by echolabs')
            ->withPrompt('Who are you?')
            ->generate();

        expect($response->text)->toBe('I am Prism, a helpful AI assistant created by echo labs.')
            ->and($response->usage->promptTokens)->toBe(17)
            ->and($response->usage->completionTokens)->toBe(14)
            ->and($response->meta->id)->toBe('')
            ->and($response->meta->model)->toBe('gemini-1.5-flash')
            ->and($response->finishReason)->toBe(FinishReason::Stop);
    });

    it('can generate text using multiple tools and multiple steps', function (): void {
        FixtureResponse::fakeResponseSequence('*', 'gemini/generate-text-with-multiple-tools');

        $tools = [
            (new Tool)
                ->as('get_weather')
                ->for('use this tool when you need to get weather for the city')
                ->withStringParameter('city', 'The city that you want the weather for')
                ->using(fn (string $city): string => 'The weather will be 45° and cold'),
            (new Tool)
                ->as('search_games')
                ->for('useful for searching current games times in the city')
                ->withStringParameter('city', 'The city that you want the game times for')
                ->using(fn (string $city): string => 'The tigers game is at 3pm in detroit'),
        ];

        $response = Prism::text()
            ->using(Provider::Gemini, 'gemini-1.5-flash')
            ->withTools($tools)
            ->withMaxSteps(5)
            ->withPrompt('What time is the tigers game today in Detroit and should I wear a coat? please check all the details from tools')
            ->generate();

        // Assert tool calls in the first step
        $firstStep = $response->steps[0];
        expect($firstStep->toolCalls)->toHaveCount(2);
        expect($firstStep->toolCalls[0]->name)->toBe('search_games');
        expect($firstStep->toolCalls[0]->arguments())->toBe([
            'city' => 'Detroit',
        ]);
        expect($firstStep->toolCalls[1]->name)->toBe('get_weather');
        expect($firstStep->toolCalls[1]->arguments())->toBe([
            'city' => 'Detroit',
        ]);

        // Assert usage (combined from both responses)
        expect($response->usage->promptTokens)->toBe(350)
            ->and($response->usage->completionTokens)->toBe(42);

        // Assert response
        expect($response->meta->id)->toBe('')
            ->and($response->meta->model)->toBe('gemini-1.5-flash')
            ->and($response->text)->toBe('The tigers game is at 3pm today in Detroit.  The weather will be 45° and cold, so you should wear a coat.');
    });

    it('handles specific tool choice', function (): void {
        FixtureResponse::fakeResponseSequence('*', 'gemini/generate-text-with-required-tool-call');

        $tools = [
            (new Tool)
                ->as('weather')
                ->for('useful when you need to search for current weather conditions')
                ->withStringParameter('city', 'The city that you want the weather for')
                ->using(fn (string $city): string => 'The weather will be 75° and sunny'),
            (new Tool)
                ->as('search')
                ->for('useful for searching curret events or data')
                ->withStringParameter('query', 'The detailed search query')
                ->using(fn (string $query): string => 'The tigers game is at 3pm in detroit'),
        ];

        $response = Prism::text()
            ->using(Provider::Gemini, 'gemini-1.5-flash')
            ->withPrompt('Do something')
            ->withTools($tools)
            ->withToolChoice('weather')
            ->generate();

        expect($response->steps[0]->toolCalls[0]->name)->toBe('weather');
    });
});

describe('Image support with Gemini', function (): void {
    it('can send images from path', function (): void {
        FixtureResponse::fakeResponseSequence('*', 'gemini/image-detection');

        $response = Prism::text()
            ->using(Provider::Gemini, 'gemini-1.5-flash')
            ->withMessages([
                new UserMessage(
                    'What is this image',
                    additionalContent: [
                        Image::fromPath('tests/Fixtures/test-image.png'),
                    ],
                ),
            ])
            ->generate();

        // Assert response
        expect($response->text)->toBe("That's an illustration of a **diamond**.  More specifically, it's a stylized, geometric representation of a diamond, often used as an icon or symbol")
            ->and($response->usage->promptTokens)->toBe(263)
            ->and($response->usage->completionTokens)->toBe(35)
            ->and($response->meta->id)->toBe('')
            ->and($response->meta->model)->toBe('gemini-1.5-flash')
            ->and($response->finishReason)->toBe(FinishReason::Stop);

        // Assert request format
        Http::assertSent(function (Request $request): bool {
            $message = $request->data()['contents'][0]['parts'];

            expect($message[0])->toBe([
                'text' => 'What is this image',
            ]);

            expect($message[1]['inline_data'])->toHaveKeys(['mime_type', 'data']);
            expect($message[1]['inline_data']['mime_type'])->toBe('image/png');
            expect($message[1]['inline_data']['data'])->toBe(
                base64_encode(file_get_contents('tests/Fixtures/test-image.png'))
            );

            return true;
        });
    });

    it('can send images from base64', function (): void {
        FixtureResponse::fakeResponseSequence('*', 'gemini/image-detection');

        $response = Prism::text()
            ->using(Provider::Gemini, 'gemini-1.5-flash')
            ->withMessages([
                new UserMessage(
                    'What is this image',
                    additionalContent: [
                        Image::fromBase64(
                            base64_encode(file_get_contents('tests/Fixtures/test-image.png')),
                            'image/png'
                        ),
                    ],
                ),
            ])
            ->generate();

        Http::assertSent(function (Request $request): bool {
            $message = $request->data()['contents'][0]['parts'];

            expect($message[0])->toBe([
                'text' => 'What is this image',
            ]);

            expect($message[1]['inline_data'])->toHaveKeys(['mime_type', 'data']);
            expect($message[1]['inline_data']['mime_type'])->toBe('image/png');
            expect($message[1]['inline_data']['data'])->toBe(
                base64_encode(file_get_contents('tests/Fixtures/test-image.png'))
            );

            return true;
        });
    });

    it('can send images from url', function (): void {
        FixtureResponse::fakeResponseSequence('*', 'gemini/image-detection');

        $image = 'https://storage.echolabs.dev/api/v1/buckets/public/objects/download?preview=true&prefix=test-image.png';

        $response = Prism::text()
            ->using(Provider::Gemini, 'gemini-1.5-flash')
            ->withMessages([
                new UserMessage(
                    'What is this image',
                    additionalContent: [
                        Image::fromUrl($image, 'image/png'),
                    ],
                ),
            ])
            ->generate();

        Http::assertSent(function (Request $request) use ($image): bool {
            $message = $request->data()['contents'][0]['parts'];

            expect($message[0])->toBe([
                'text' => 'What is this image',
            ]);

            expect($message[1]['inline_data'])->toHaveKeys(['mime_type', 'data']);
            expect($message[1]['inline_data']['mime_type'])->toBe('image/png');
            expect($message[1]['inline_data']['data'])->toBe(
                base64_encode(file_get_contents($image))
            );

            return true;
        });
    });
});

describe('Document support for Gemini', function (): void {
    it('can read process pdf documents', function (): void {
        FixtureResponse::fakeResponseSequence('*', 'gemini/text-with-pdf-documents');

        $response = Prism::text()
            ->using(Provider::Gemini, 'gemini-2.0-flash')
            ->withMessages([
                new UserMessage(
                    content: 'What is this document about?',
                    additionalContent: [
                        Document::fromBase64(base64_encode(file_get_contents('tests/Fixtures/test-pdf.pdf')), 'application/pdf'),
                    ]
                ),
            ])
            ->generate();

        expect($response->text)->toBe("The document is about the answer to the Ultimate Question of Life, the Universe, and Everything, which is stated to be 42. This is a reference to the science fiction series \"The Hitchhiker's Guide to the Galaxy\" by Douglas Adams.\n");

        Http::assertSent(function (Request $request): bool {
            $message = $request->data()['contents'][0]['parts'];

            expect($message[1])->toBe([
                'text' => 'What is this document about?',
            ]);

            expect($message[0]['inline_data'])->toHaveKeys(['mime_type', 'data']);

            expect($message[0]['inline_data']['mime_type'])->toBe('application/pdf');

            expect($message[0]['inline_data']['data'])->toBe(
                base64_encode(file_get_contents('tests/Fixtures/test-pdf.pdf'))
            );

            return true;
        });
    });

    it('can read process text documents', function (): void {
        FixtureResponse::fakeResponseSequence('*', 'gemini/text-with-text-documents');

        $response = Prism::text()
            ->using(Provider::Gemini, 'gemini-2.0-flash')
            ->withMessages([
                new UserMessage(
                    content: 'What is this document about?',
                    additionalContent: [
                        Document::fromText(file_get_contents('tests/Fixtures/test-text.txt')),
                    ]
                ),
            ])
            ->generate();

        expect($response->text)->toBe("This document is about the number 42 and its significance, likely referencing the book \"The Hitchhiker's Guide to the Galaxy\" by Douglas Adams. In that book, a supercomputer called Deep Thought calculates that 42 is the answer to the Ultimate Question of Life, the Universe, and Everything. However, frustratingly, no one knows what the actual question *is*.\n\nTherefore, the document could be:\n\n*   **An explanation of the concept of 42 within the context of *The Hitchhiker's Guide to the Galaxy***: This is the most likely scenario.\n*   **A humorous exploration of possible interpretations of 42**: Playing on the ambiguity of the answer.\n*   **A coincidence**: The document could be about something completely unrelated to the book, and the mention of 42 is just a bizarre coincidence. However, given the specific phrasing (\"The Answer to the Ultimate Question...\"), this is very unlikely.\n*   **A piece of fan fiction or creative writing**: Using the 42 concept as a jumping-off point.\n\nIn short, it's almost certainly related to *The Hitchhiker's Guide to the Galaxy* and the significance of the number 42 within that fictional universe.\n");

        Http::assertSent(function (Request $request): bool {
            $message = $request->data()['contents'][0]['parts'];

            expect($message[1])->toBe([
                'text' => 'What is this document about?',
            ]);

            expect($message[0]['inline_data'])->toHaveKeys(['mime_type', 'data']);

            expect($message[0]['inline_data']['mime_type'])->toBe('text/plain');

            expect($message[0]['inline_data']['data'])->toBe(
                base64_encode(file_get_contents('tests/Fixtures/test-text.txt'))
            );

            return true;
        });
    });
});

describe('search grounding', function (): void {
    it('adds the google_search empty tool if searchGrounding is set to true', function (): void {
        FixtureResponse::fakeResponseSequence('*', 'gemini/generate-text-with-search-grounding');

        Prism::text()
            ->using(Provider::Gemini, 'gemini-2.0-flash')
            ->withPrompt('What is the stock price of Google right now?')
            ->withProviderMeta(Provider::Gemini, ['searchGrounding' => true])
            ->generate();

        Http::assertSent(function (Request $request): true {
            $data = $request->data();

            expect($data['tools'][0])->toHaveKey('google_search');
            expect($data['tools'][0]['google_search'])->toBeObject();

            return true;
        });
    });

    it('throws an exception of searchGrounding is enabled with other tools', function (): void {
        Http::fake()->preventStrayRequests();

        $tools = [
            (new Tool)
                ->as('search_games')
                ->for('useful for searching current games times in the city')
                ->withStringParameter('city', 'The city that you want the game times for')
                ->using(fn (string $city): string => 'The tigers game is at 3pm in detroit'),
        ];

        Prism::text()
            ->using(Provider::Gemini, 'gemini-2.0-flash')
            ->withMaxSteps(3)
            ->withTools($tools)
            ->withPrompt('What sport fixtures are on today, and will I need a coat based on today\'s weather forecast?')
            ->withProviderMeta(Provider::Gemini, ['searchGrounding' => true])
            ->generate();
    })->throws(PrismException::class, 'Use of search grounding with custom tools is not currently supported by Prism.');

    it('uses search grounding where searchGrounding is true on provider meta', function (): void {
        FixtureResponse::fakeResponseSequence('*', 'gemini/generate-text-with-search-grounding');

        $response = Prism::text()
            ->using(Provider::Gemini, 'gemini-2.0-flash')
            ->withPrompt('What is the stock price of Google right now?')
            ->withProviderMeta(Provider::Gemini, ['searchGrounding' => true])
            ->generate();

        expect($response->text)->toContain('Alphabet Inc.');
    });

    it('maps search groundings into additional content', function (): void {
        FixtureResponse::fakeResponseSequence('*', 'gemini/generate-text-with-search-grounding');

        $response = Prism::text()
            ->using(Provider::Gemini, 'gemini-2.0-flash')
            ->withPrompt('What is the stock price of Google right now?')
            ->withProviderMeta(Provider::Gemini, ['searchGrounding' => true])
            ->generate();

        expect($response->additionalContent)->toHaveKey('searchEntryPoint');
        expect($response->additionalContent)->toHaveKey('searchQueries');
        expect($response->additionalContent)->toHaveKey('groundingSupports');

        expect($response->additionalContent['searchEntryPoint'])->not()->toBe('');
        expect($response->additionalContent['searchQueries'])->toHaveCount(1);
        expect($response->additionalContent['groundingSupports'])->toHaveCount(4);

        expect($response->additionalContent['groundingSupports'][0])->toBeInstanceOf(MessagePartWithSearchGroundings::class);
        expect($response->additionalContent['groundingSupports'][0]->text)->not()->toBe('');
        expect($response->additionalContent['groundingSupports'][0]->startIndex)->not()->toBe(0);
        expect($response->additionalContent['groundingSupports'][0]->endIndex)->not()->toBe(0);
        expect($response->additionalContent['groundingSupports'][0]->groundings)->toHaveCount(1);
        expect($response->additionalContent['groundingSupports'][0]->groundings[0])->toBeInstanceOf(SearchGrounding::class);
        expect($response->additionalContent['groundingSupports'][0]->groundings[0]->title)->not()->toBe('');
        expect($response->additionalContent['groundingSupports'][0]->groundings[0]->uri)->not()->toBe('');
        expect($response->additionalContent['groundingSupports'][0]->groundings[0]->confidence)->not()->toBe(0.0);
    });
});

describe('Cache support for Gemini', function (): void {
    it('can use a cache object with a text request', function (): void {
        FixtureResponse::fakeResponseSequence('*', 'gemini/use-cache-with-text');

        /** @var Gemini */
        $provider = Prism::provider(Provider::Gemini);

        $object = $provider->cache(
            model: 'gemini-1.5-flash-002',
            messages: [
                new UserMessage('', [
                    Document::fromPath('tests/Fixtures/long-document.pdf'),
                ]),
            ],
            systemPrompts: [
                new SystemMessage('You are a legal analyst.'),
            ],
            ttl: 30
        );

        $response = Prism::text()
            ->using(Provider::Gemini, 'gemini-1.5-flash-002')
            ->withProviderMeta(Provider::Gemini, ['cachedContentName' => $object->name])
            ->withPrompt('In no more than 100 words, what is the document about?')
            ->generate();

        Http::assertSentInOrder([
            fn (Request $request): bool => true,
            fn (Request $request): bool => $request->data()['cachedContent'] === $object->name,
        ]);

        expect($response->text)->toBe("That's the Consolidated Version of the Treaty on the Functioning of the European Union (TFEU), adopted on 25 March 1957.  It outlines the principles, competencies, and policies of the European Union.  The TFEU organizes the EU's functioning and details its areas of competence, including exclusive, shared, and supporting competences.  It also covers non-discrimination, citizenship, and various EU policies (e.g., internal market, agriculture, and justice).  Finally, it sets out institutional and financial provisions.\n");

        expect($response->usage->promptTokens)->toBe(16);
        expect($response->usage->completionTokens)->toBe(116);
        expect($response->usage->cacheReadInputTokens)->toBe(88759);
    });
});
