<?php

namespace Tests\Feature;

use App\Agent\Choices;
use App\Agent\ToolRegistry;
use App\Agent\Workspace;
use App\Campaigns\Targeting\SearchKeywordSelections;
use App\Models\Brief;
use App\Models\Campaign;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Ai\Tools\Request;
use RuntimeException;
use Tests\TestCase;

/**
 * The keyword question offered no way to use what it promised.
 *
 * It says "you can also specify match types and negative keywords" and
 * "choose as many as you need", and then Other was a bare one-line box with
 * the placeholder "Enter your value". Reported from the browser: the buyer
 * could type one keyword and nothing else, with no clarity at all.
 */
class TypedSearchKeywordsKeepTheirMarkersMeaningTest extends TestCase
{
    use RefreshDatabase;

    private function campaign(bool $withPageKeywords = false): Campaign
    {
        $user = User::factory()->create();
        $this->actingAs($user);

        $campaign = Campaign::create([
            'user_id' => $user->getKey(),
            'name' => 'Typed keyword test',
            'platform' => 'google',
            'campaign_type' => 'search',
            'status' => 'draft',
            'ad_account_id' => '1234567890',
            'locations' => ['countries' => ['US']],
        ]);

        // The question is only offered when the page yielded something to show,
        // so a brief is needed to see it at all.
        if ($withPageKeywords) {
            $brief = Brief::create([
                'user_id' => $user->getKey(),
                'landing_url' => 'https://example.com/flights',
                'page_analysis' => [
                    'url' => 'https://example.com/flights',
                    'title' => 'Flights to Italy',
                    'keywords' => ['cheap flights to italy', 'rome city break'],
                ],
            ]);
            $campaign->forceFill(['brief_id' => $brief->id])->save();
            $campaign = $campaign->fresh();
        }

        app(Workspace::class)->bindTo('typed-keyword-conversation');
        app(Workspace::class)->focusOn($campaign);

        return $campaign;
    }

    public function test_the_question_says_how_to_type_match_types_and_exclusions(): void
    {
        $this->campaign(withPageKeywords: true);
        $tool = collect(app(ToolRegistry::class)->resolve())
            ->first(fn ($candidate): bool => $candidate->name() === 'campaign__set_search_keywords');

        $this->assertNotNull($tool);
        $tool->handle(new Request([]));

        $offer = collect(app(Choices::class)->all())
            ->firstWhere('field', 'google_search_keywords');

        $this->assertNotNull($offer, 'The keyword question was not offered.');
        $this->assertTrue($offer['allow_other']);
        $this->assertTrue($offer['multiple']);

        // Without these the buyer is told the capability exists and never how
        // to reach it, which is the defect as reported.
        $this->assertNotNull($offer['other_hint']);
        $this->assertNotNull($offer['other_placeholder']);

        foreach (['phrase', 'exact', 'comma'] as $term) {
            $this->assertStringContainsStringIgnoringCase(
                $term,
                $offer['other_hint'],
                'The hint does not explain '.$term.'.',
            );
        }

        // Shown by example rather than described, so several at once is
        // obviously allowed.
        $this->assertStringContainsString(',', $offer['other_placeholder']);
    }

    public function test_googles_shorthand_sets_the_match_type_rather_than_being_saved_as_text(): void
    {
        $campaign = $this->campaign();

        $saved = app(SearchKeywordSelections::class)->save($campaign, [
            ['text' => '"rome city break"', 'match_type' => 'BROAD', 'negative' => false],
            ['text' => '[milan flights]', 'match_type' => 'BROAD', 'negative' => false],
            ['text' => '-free', 'match_type' => 'BROAD', 'negative' => false],
            ['text' => 'cheap flights to italy', 'match_type' => 'BROAD', 'negative' => false],
        ], 0);

        $criteria = app(SearchKeywordSelections::class)->criteria($campaign->fresh());

        $this->assertSame([
            ['text' => 'rome city break', 'match_type' => 'PHRASE', 'negative' => false, 'provenance' => 'user'],
            ['text' => 'milan flights', 'match_type' => 'EXACT', 'negative' => false, 'provenance' => 'user'],
            ['text' => 'free', 'match_type' => 'BROAD', 'negative' => true, 'provenance' => 'user'],
            ['text' => 'cheap flights to italy', 'match_type' => 'BROAD', 'negative' => false, 'provenance' => 'user'],
        ], $criteria);

        $this->assertGreaterThan(0, $saved->revision);
    }

    public function test_a_hyphen_inside_a_keyword_is_not_an_exclusion(): void
    {
        $campaign = $this->campaign();

        app(SearchKeywordSelections::class)->save($campaign, [
            ['text' => 't-shirts for men', 'match_type' => 'BROAD', 'negative' => false],
        ], 0);

        $criteria = app(SearchKeywordSelections::class)->criteria($campaign->fresh());

        $this->assertSame('t-shirts for men', $criteria[0]['text']);
        $this->assertFalse($criteria[0]['negative']);
    }

    public function test_a_term_that_is_only_markers_is_still_refused(): void
    {
        $campaign = $this->campaign();

        // "-" alone leaves nothing to bid on. Stripping the marker must not
        // turn an empty keyword into a saved one.
        $this->expectException(RuntimeException::class);

        app(SearchKeywordSelections::class)->save($campaign, [
            ['text' => '-', 'match_type' => 'BROAD', 'negative' => false],
        ], 0);
    }
}
