<?php
namespace boru\ai\Tests\AI;

use boru\ai\AI;
use boru\ai\Conversation\Conversation;
use boru\ai\Conversation\ConversationReference;
use boru\ai\Conversation\Turn;
use boru\ai\Runtime\RuntimeContext;
use boru\ai\Tests\Fakes\FakePersistenceProvider;
use PHPUnit\Framework\TestCase;

class AIConversationForkFacadeTest extends TestCase
{
    protected function setUp(): void
    {
        AI::runtimeContext(new RuntimeContext());
    }

    public function testStaticForkConversationUsesConfiguredPersistence()
    {
        $persistence = new FakePersistenceProvider();
        $persistence->loadedConversation = $this->buildConversation();
        AI::persistence($persistence);

        $target = AI::forkConversation('source_ref', 'target_ref');

        $this->assertSame('target_ref', $target->reference()->externalReference());
        $this->assertCount(1, $persistence->savedConversations);
        $this->assertCount(1, $persistence->savedTurns);
    }

    public function testInstanceForkToUsesCurrentConversationReference()
    {
        $persistence = new RecordingReferencePersistenceProvider();
        $persistence->loadedConversation = $this->buildConversation();
        AI::persistence($persistence);

        AI::provider('gemini')
            ->reference('source_ref', 'user_1')
            ->forkTo('target_ref');

        $this->assertSame('source_ref', $persistence->loadedReferences[0]->externalReference());
        $this->assertSame('user_1', $persistence->loadedReferences[0]->userId());
    }

    protected function buildConversation()
    {
        $reference = new ConversationReference();
        $reference->id('source_conv')->externalReference('source_ref');

        $conversation = new Conversation($reference);
        $conversation->provider('gemini')->model('gemini-2.5-pro');
        $conversation->addTurn((new Turn())->number(1)->status('completed'));
        return $conversation;
    }
}

class RecordingReferencePersistenceProvider extends FakePersistenceProvider
{
    public $loadedReferences = array();

    public function loadConversation(ConversationReference $reference)
    {
        $this->loadedReferences[] = $reference;
        return parent::loadConversation($reference);
    }
}
