<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\Targeting\GoogleKeywordIdeas;
use App\Campaigns\Targeting\SearchKeywordSelections;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use RuntimeException;
use Stringable;

class SetSearchKeywords implements Tool
{
    use ActsOnFocusedCampaign;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Choices $choices,
        private readonly SearchKeywordSelections $keywords,
        private readonly GoogleKeywordIdeas $ideas,
    ) {}

    public function description(): Stringable|string
    {
        return 'Review or replace Google Search keywords on the draft campaign in focus. '
            .'Call without keywords to show current terms and landing-page suggestions. '
            .'Save the complete intended set with text, BROAD/PHRASE/EXACT match type, '
            .'and negative=true for exclusions. Never invent terms the user has not selected. '
            .'Include the latest targeting revision to reject stale changes. '
            .'Use clear=true to remove an explicit selection, including after a draft changes away from Search. '
            .'Pass research=true to request read-only Google keyword ideas for the campaign’s verified geography and English language.';
    }

    public function handle(Request $request): Stringable|string
    {
        if (! $campaign = $this->focused()) {
            return $this->noCampaign();
        }

        $arguments = $request->all();
        $clearing = ($arguments['clear'] ?? false) === true;

        if ($campaign->platform !== 'google' || $campaign->isPublished()
            || (($campaign->campaign_type ?: 'search') !== 'search' && ! $clearing)) {
            return $this->json(['ok' => false, 'error' => 'Keyword selection is available for draft Google Search campaigns only.']);
        }

        $revision = (int) ($campaign->targetingSet()->value('revision') ?? 0);

        if ($clearing) {
            if (! isset($arguments['expected_revision'])) {
                return $this->json(['ok' => false, 'error' => 'Provide the latest targeting revision to clear Search keyword choices.']);
            }

            try {
                $set = $this->keywords->clear($campaign, (int) $arguments['expected_revision']);

                return $this->json(['ok' => true, 'revision' => $set->revision, 'keywords' => []]);
            } catch (RuntimeException $exception) {
                return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
            }
        }

        if (($arguments['research'] ?? false) === true) {
            try {
                return $this->json(['ok' => true, 'revision' => $revision, 'research' => $this->ideas->forCampaign($campaign)]);
            } catch (RuntimeException $exception) {
                return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
            }
        }

        if (! array_key_exists('keywords', $arguments)) {
            try {
                $current = $this->keywords->criteria($campaign);
            } catch (RuntimeException $exception) {
                return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
            }

            $this->choices->offerSearchKeywords(
                question: 'Which Search keywords should this campaign use? Pick one or more match types on each, and add negative keywords below.',
                // Each option carries its own match type and the revision the
                // question was asked at, so a click can be applied without a
                // model turn. Answers needs both: the match type because a
                // suggestion keeps the one it was offered with, and the
                // revision because that is what makes a stale click fail
                // loudly instead of overwriting a newer selection.
                options: array_map(static fn (array $item): array => [
                    'value' => $item['text'],
                    'label' => $item['text'],
                    'hint' => $item['match_type'].' match',
                    'sends' => 'Use the Search keyword '.$item['text'],
                    'revision' => $revision,
                    'arguments' => ['match_type' => $item['match_type']],
                ], array_values(array_filter($current, static fn (array $item): bool => ! $item['negative']))),
                matchTypes: SearchKeywordSelections::MATCH_TYPES,
                // The question promises match types and negative keywords and
                // nothing told the buyer how to express either, so Other read
                // as a box for one more term. Google's own shorthand is what
                // this audience already types into Google, and the placeholder
                // shows it rather than describing it.
                otherHint: 'Add your own, comma separated: "quoted" is phrase, [bracketed] is exact, -minus excludes.',
                otherPlaceholder: 'cheap flights to italy, "rome city break", [milan flights], -free',
            );

            return $this->json(['ok' => true, 'revision' => $revision, 'keywords' => $current]);
        }

        if (! is_array($arguments['keywords']) || ! isset($arguments['expected_revision'])) {
            return $this->json(['ok' => false, 'error' => 'Send the complete keyword list and its current targeting revision.']);
        }

        try {
            $set = $this->keywords->save($campaign, $arguments['keywords'], (int) $arguments['expected_revision']);

            return $this->json([
                'ok' => true,
                'revision' => $set->revision,
                'keywords' => $this->keywords->criteria($campaign),
            ]);
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'keywords' => $schema->array()->items($schema->object([
                'text' => $schema->string()->required(),
                'match_type' => $schema->string()->description('BROAD, PHRASE, or EXACT.')->required(),
                'negative' => $schema->boolean()->description('True to exclude searches matching this term.'),
            ]))->description('Complete selected keyword set. Omit to review current terms.'),
            'expected_revision' => $schema->integer()->description('Targeting revision from the most recent review.'),
            'research' => $schema->boolean()->description('Read-only Google keyword ideas for the campaign’s exact geography.'),
            'clear' => $schema->boolean()->description('Clear explicit Search keyword choices, including after switching away from Search.'),
        ];
    }
}
