<?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\LocationDiscovery;
use App\Campaigns\Targeting\PublishedLocationChangePlanner;
use App\Campaigns\Targeting\TargetingSelections;
use App\Models\Campaign;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Auth;
use InvalidArgumentException;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use RuntimeException;
use Stringable;

class PreviewPublishedLocationChange implements Tool
{
    use ActsOnFocusedCampaign;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Choices $choices,
        private readonly TargetingSelections $selections,
        private readonly LocationDiscovery $discovery,
        private readonly PublishedLocationChangePlanner $planner,
    ) {}

    public function description(): Stringable|string
    {
        return 'Preview a city or region addition, removal, or one-step replacement on the focused published Meta or Google campaign. '
            .'Search within a selected country, choose the exact provider result, then show the before/after targeting. '
            .'This verifies a provider place and reads the current campaign but never edits campaign targeting or the ad platform. '
            .'The preview never applies a change; use the separately approved apply tool only if it is enabled. '
            .'A country, state, city, or ZIP change on an ad set that is already live is edit_entity, not this preview.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'operation' => $schema->string()->description('add, remove, or replace a city/region.')->required(),
            'country_code' => $schema->string()->description('Selected two-letter country code; needed for an add or replace search.'),
            'kind' => $schema->string()->description('city or region; needed for an add or replace search.'),
            'query' => $schema->string()->description('At least two characters of the place name for an add or replace search.'),
            'page' => $schema->integer()->description('Meta page 1 to 4; Google only page 1.'),
            'external_id' => $schema->string()->description('Exact provider ID from a search result; use with the same query to preview adding or replacing it.'),
            'mapping_id' => $schema->integer()->description('Saved mapping ID from the selected-place list; use to preview removing it.'),
            'replace_mapping_id' => $schema->integer()->description('Existing selected mapping ID to replace. Choose this before searching for its replacement.'),
            'expected_revision' => $schema->integer()->description('Targeting revision shown with the search or selected-place list.'),
        ];
    }

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

        if (Auth::id() === null || (string) Auth::id() !== (string) $campaign->user_id) {
            return $this->json(['ok' => false, 'error' => 'This campaign does not belong to the signed-in user.']);
        }

        if (! $campaign->isPublished() || ! in_array($campaign->platform, ['meta', 'google'], true)) {
            return $this->json(['ok' => false, 'error' => 'Choose a published Meta or Google campaign to preview a location change.']);
        }

        $args = $request->all();
        $operation = strtolower(trim((string) ($args['operation'] ?? '')));
        $revision = (int) ($campaign->targetingSet()->value('revision') ?? 0);

        if (! in_array($operation, ['add', 'remove', 'replace'], true)) {
            return $this->json(['ok' => false, 'error' => 'Choose add, remove, or replace.']);
        }

        try {
            if ($operation === 'remove') {
                if (! isset($args['mapping_id'])) {
                    $places = $this->selections->reviewedCampaignPlaces($campaign);
                    $this->choices->offer(
                        field: $campaign->platform.'_published_location_removal',
                        question: 'Which selected city or region should be removed?',
                        options: array_map(fn (array $place): array => [
                            'value' => (string) $place['mapping_id'],
                            'label' => $place['label'],
                            'hint' => ucfirst((string) $campaign->platform).' ID '.$place['external_id'],
                            'sends' => sprintf('Preview removing %s mapping %s at targeting revision %d', $place['label'], $place['mapping_id'], $revision),
                        ], array_values(array_filter($places, fn (array $place): bool => $place['mapping_id'] !== null))),
                    );

                    return $this->json(['ok' => true, 'selected_places' => $places, 'revision' => $revision, 'note' => 'Choose a place to preview its removal. Nothing has changed.']);
                }

                return $this->preview($campaign, 'remove', (int) $args['mapping_id'], $args);
            }

            $replacedPlace = null;

            if ($operation === 'replace') {
                $places = $this->selections->reviewedCampaignPlaces($campaign);

                if (! isset($args['replace_mapping_id'])) {
                    $this->choices->offer(
                        field: $campaign->platform.'_published_location_replacement',
                        question: 'Which selected city or region should be replaced?',
                        options: array_map(fn (array $place): array => [
                            'value' => (string) $place['mapping_id'],
                            'label' => $place['label'],
                            'hint' => ucfirst((string) $campaign->platform).' ID '.$place['external_id'],
                            'sends' => sprintf('Replace %s mapping %s with a different verified place in %s at targeting revision %d',
                                $place['label'], $place['mapping_id'], $place['country_code'], $revision),
                        ], array_values(array_filter($places, fn (array $place): bool => $place['mapping_id'] !== null))),
                    );

                    return $this->json(['ok' => true, 'selected_places' => $places, 'revision' => $revision, 'note' => 'Choose the existing place, then search for its replacement in the same country. Nothing has changed.']);
                }

                $replacedPlace = collect($places)->first(fn (array $place): bool => $place['mapping_id'] === (int) $args['replace_mapping_id']);

                if ($replacedPlace === null) {
                    throw new RuntimeException('Choose a city or region currently selected on this campaign to replace.');
                }
            }

            $countryCode = strtoupper(trim((string) ($args['country_code'] ?? $replacedPlace['country_code'] ?? '')));
            $kind = strtolower(trim((string) ($args['kind'] ?? '')));
            $kind = in_array($kind, ['state', 'province'], true) ? 'region' : $kind;
            $term = trim((string) ($args['query'] ?? ''));
            $page = (int) ($args['page'] ?? 1);

            if (! in_array($countryCode, $this->selections->countries($campaign), true)) {
                throw new RuntimeException('Choose a country already selected on this campaign.');
            }

            if ($replacedPlace !== null && $countryCode !== $replacedPlace['country_code']) {
                throw new RuntimeException('Choose a replacement within the selected place’s country.');
            }

            if (filled($args['external_id'] ?? null)) {
                if (! isset($args['expected_revision']) || (int) $args['expected_revision'] !== $revision) {
                    throw new RuntimeException('Targeting changed since the place search. Search and review again.');
                }

                $mapping = $this->discovery->select(
                    $campaign->platform, $kind, $countryCode, $term,
                    (string) $args['external_id'], $campaign->ad_account_id, $page,
                );

                return $this->preview($campaign, $operation, $mapping->getKey(), $args);
            }

            $matches = $this->discovery->search($campaign->platform, $kind, $countryCode, $term, $campaign->ad_account_id, $page);
            $this->choices->offer(
                field: $campaign->platform.'_published_location_'.($operation === 'replace' ? 'replacement' : 'addition'),
                question: $operation === 'replace' ? 'Which exact city or region should replace the selected place?' : 'Which exact city or region should be previewed?',
                options: array_map(fn (array $match): array => [
                    'value' => $match['external_id'],
                    'label' => $match['label'],
                    'hint' => ucfirst((string) $campaign->platform).' ID '.$match['external_id'],
                    'sends' => sprintf('Preview %s %s (%s ID %s) from search "%s" in %s at targeting revision %d%s',
                        $operation === 'replace' ? 'replacing with' : 'adding', $match['label'], ucfirst((string) $campaign->platform), $match['external_id'], $term, $countryCode, $revision,
                        $replacedPlace === null ? '' : ' while replacing mapping '.$replacedPlace['mapping_id']),
                ], $matches),
            );

            return $this->json([
                'ok' => $matches !== [], 'matches' => $matches, 'revision' => $revision,
                'replace_mapping_id' => $replacedPlace['mapping_id'] ?? null,
                'note' => 'Choose the exact result to preview it. Nothing has changed.',
            ]);
        } catch (RuntimeException|InvalidArgumentException|ConnectionException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }
    }

    /** @param array<string, mixed> $args */
    private function preview(Campaign $campaign, string $operation, int $mappingId, array $args): string
    {
        if (! isset($args['expected_revision'])) {
            throw new RuntimeException('Provide the targeting revision shown with the place choices.');
        }

        $plan = $operation === 'replace'
            ? $this->planner->preview($campaign, $operation, $mappingId, (int) $args['expected_revision'], (int) ($args['replace_mapping_id'] ?? 0))
            : $this->planner->preview($campaign, $operation, $mappingId, (int) $args['expected_revision']);

        return $this->json([
            'ok' => true,
            ...$plan,
            'applied' => false,
            'note' => config('platforms.guardrails.published_location_edits_enabled', false)
                ? 'Preview only. Campaign targeting and the ad platform are unchanged. A separate approved apply action is required.'
                : 'Preview only. Campaign targeting and the ad platform are unchanged. Published-location edits are not enabled yet.',
        ]);
    }
}
