<?php

namespace Tests\Feature;

use App\Agent\MarketingAgent;
use App\Agent\NamespacedTool;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Laravel\Ai\Tools\Request;
use Tests\TestCase;

/**
 * A clarification the user has already answered is not asked again unchanged.
 *
 * From 12 Oct. "give me a list of campaigns and adsets in autoautomotive
 * account" was answered with "Which ad account would you like to check?" and
 * two options, neither of them the account named. The reply "auto automotive"
 * produced the same question and the same two options again, and the
 * conversation stopped there. Nothing told the buyer that the account they had
 * named twice was not one this instance can reach - only two were on the allow
 * list - so there was no answer they could have given.
 *
 * The guard is deterministic rather than a prompt rule, because the turn that
 * repeats the question is the same turn that already failed to answer it:
 * advice does not help a model that has run out of moves. What it returns is a
 * refusal carrying the user's own words and the options it gave, so the model
 * has everything it needs to say "that is not one of these, here is what is".
 *
 * Only an exact repeat is refused. Widening the answers is the fix, not the
 * fault, and must still be allowed.
 */
class TheSameQuestionIsNotAskedTwiceTest extends TestCase
{
    use RefreshDatabase;

    private User $user;

    protected function setUp(): void
    {
        parent::setUp();

        $this->user = User::factory()->create();
        $this->actingAs($this->user);

        app(Workspace::class)->bindTo('conv-clarify');
        app(Workspace::class)->ownedBy($this->user);
    }

    private function tool(): NamespacedTool
    {
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($t): bool => $t->name() === 'workspace__offer_clarification');

        $this->assertNotNull($tool, 'workspace__offer_clarification is not registered');

        return $tool;
    }

    /** @param list<string> $options */
    private function ask(string $question, array $options): array
    {
        return json_decode(
            (string) $this->tool()->handle(new Request(['question' => $question, 'options' => $options])),
            true,
        );
    }

    /** What last turn left on screen, which is how the tool knows it is repeating. */
    private function lastTurnOffered(string $question, array $options): void
    {
        app(Workspace::class)->rememberChoices([[
            'field' => 'clarification',
            'question' => $question,
            'options' => array_map(
                static fn (string $o): array => ['value' => $o, 'label' => $o],
                $options,
            ),
        ]]);
    }

    private function userSaid(string $text): void
    {
        DB::table('agent_conversation_messages')->insert([
            'id' => (string) Str::uuid(),
            'conversation_id' => 'conv-clarify',
            'participant_type' => $this->user->getMorphClass(),
            'participant_id' => $this->user->id,
            'agent' => MarketingAgent::class,
            'role' => 'user',
            'content' => $text,
            'attachments' => '[]',
            'tool_calls' => '[]',
            'tool_results' => '[]',
            'usage' => '[]',
            'meta' => '[]',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    // ------------------------------------------------------------- the loop

    /** The 12 Oct sequence, exactly. */
    public function test_the_same_question_with_the_same_answers_is_refused(): void
    {
        $question = 'Which ad account would you like to check?';
        $options = ['MidoWeb-WWBlog-GMT-RSOC', 'StockPrices'];

        $this->lastTurnOffered($question, $options);
        $this->userSaid('auto automotive');

        $result = $this->ask($question, $options);

        $this->assertFalse($result['ok']);
        $this->assertStringContainsString('asked this question last turn', $result['error']);
    }

    /** The refusal carries what the user typed, so the model can name it back. */
    public function test_the_refusal_carries_the_users_own_words(): void
    {
        $question = 'Which ad account would you like to check?';
        $options = ['MidoWeb-WWBlog-GMT-RSOC', 'StockPrices'];

        $this->lastTurnOffered($question, $options);
        $this->userSaid('auto automotive');

        $result = $this->ask($question, $options);

        $this->assertSame('auto automotive', $result['they_said']);
        $this->assertSame($options, $result['you_offered']);
        $this->assertStringContainsString('not one of these', $result['note']);
    }

    /** And it tells the model to answer in prose rather than reach for the tool again. */
    public function test_it_sends_the_model_back_to_prose(): void
    {
        $question = 'Which ad account would you like to check?';
        $options = ['A', 'B'];

        $this->lastTurnOffered($question, $options);
        $this->userSaid('something else');

        $this->assertStringContainsString('do not call this tool again', $this->ask($question, $options)['note']);
    }

    /** Punctuation and case are not a way around it. */
    public function test_the_same_question_reworded_only_by_case_is_still_a_repeat(): void
    {
        $this->lastTurnOffered('Which ad account would you like to check?', ['A', 'B']);
        $this->userSaid('auto automotive');

        $this->assertFalse($this->ask('which ad account would you like to check', ['b', 'A'])['ok']);
    }

    // --------------------------------------------------------- still allowed

    /**
     * Widening the answers is the fix, not the fault.
     *
     * The two-option list was the problem; offering the account they named is
     * exactly what should happen next, and must not be blocked.
     */
    public function test_the_same_question_with_more_answers_is_allowed(): void
    {
        $question = 'Which ad account would you like to check?';

        $this->lastTurnOffered($question, ['MidoWeb-WWBlog-GMT-RSOC', 'StockPrices']);
        $this->userSaid('auto automotive');

        $result = $this->ask($question, ['MidoWeb-WWBlog-GMT-RSOC', 'StockPrices', 'AutoAutomotive']);

        $this->assertTrue($result['ok'], $result['error'] ?? '');
    }

    /** A different question is ordinary progress. */
    public function test_a_different_question_is_allowed(): void
    {
        $this->lastTurnOffered('Which ad account would you like to check?', ['A', 'B']);
        $this->userSaid('auto automotive');

        $this->assertTrue($this->ask('Which page should the ads run from?', ['A', 'B'])['ok']);
    }

    /** The first time it is asked there is nothing to repeat. */
    public function test_the_first_offer_is_allowed(): void
    {
        $this->assertTrue($this->ask('Is $10 the total or per day?', ['Total', 'Per day'])['ok']);
    }

    /**
     * Only a previous clarification counts, not any previous question.
     *
     * A domain tool's own offer lives in the same store under its own field.
     * Matching on question and answers alone would let objective's card block
     * a clarification that happens to read the same way, so the question and
     * the answers here are deliberately identical to the stored ones: the
     * field is the only thing keeping this allowed.
     */
    public function test_a_previous_offer_for_another_field_does_not_block_it(): void
    {
        app(Workspace::class)->rememberChoices([[
            'field' => 'objective',
            'question' => 'Which objective?',
            'options' => [
                ['value' => 'Leads', 'label' => 'Leads'],
                ['value' => 'Sales', 'label' => 'Sales'],
            ],
        ]]);
        $this->userSaid('leads');

        $this->assertTrue($this->ask('Which objective?', ['Leads', 'Sales'])['ok']);
    }
}
