<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\NameMatch;
use App\Models\ArtifactFieldSource;
use App\Models\Campaign;
use App\Models\GoogleAdsConnection;
use App\Services\GoogleAdsService;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use Carbon\Carbon;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use RuntimeException;
use Stringable;

/**
 * List conversion pixels, or attach one to the campaign in focus.
 *
 * The list merges the account's own pixels with those owned by its parent
 * business, because the one an advertiser means is frequently business owned
 * and shared rather than assigned to the account.
 */
class ChoosePixel implements Tool
{
    use ActsOnFocusedCampaign;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Meta $meta,
        private readonly Choices $choices,
        private readonly GoogleAdsService $google,
    ) {}

    public function description(): Stringable|string
    {
        return 'List available conversion pixels, or set one on the campaign in focus by passing '
            .'pixel_id. Sales and leads objectives need a pixel; traffic does not.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'pixel_id' => $schema->string()
                ->description('Set this pixel on the campaign. Omit to list the available pixels instead.'),
            'also_count' => $schema->array()->items($schema->string())
                ->description('Google only. Further conversion actions this campaign should also '
                    .'optimise toward, as resource names from the same list. Use when the buyer '
                    .'names more than one thing worth counting - a purchase and a lead, say. '
                    .'Leave empty to count only pixel_id.'),
        ];
    }

    /**
     * What counts a conversion on this platform, as one shape.
     *
     * Meta calls it a pixel and Google calls it a conversion action. They are
     * the same answer to the same question, they are both account scoped, and
     * both end up in the campaign's pixel_id, so the tool that asks is shared
     * and only the lookup differs.
     *
     * A Google resource name is the full customers/123/conversionActions/456
     * path, because that is what the API takes; it is never shown, the
     * conversion action's own name is.
     *
     * @return list<array{id: string, name: string, hint?: ?string}>
     */
    private function candidates(Campaign $campaign, bool $fresh = false): array
    {
        if ($campaign->platform !== 'google') {
            return array_map(fn (array $pixel): array => [
                'id' => (string) $pixel['id'],
                'name' => (string) ($pixel['name'] ?? $pixel['id']),
                // Last fired says more about whether it is the right pixel than
                // the name does, since names repeat across a business.
                'hint' => isset($pixel['last_fired_time'])
                    ? 'last fired '.Carbon::parse($pixel['last_fired_time'])->diffForHumans()
                    : null,
            ], collect($this->meta->on($campaign->id, 'agent')->pixels($campaign->ad_account_id, fresh: $fresh))
                ->sortByDesc(fn (array $pixel): int => isset($pixel['last_fired_time'])
                    ? Carbon::parse($pixel['last_fired_time'])->timestamp
                    : PHP_INT_MIN)
                ->values()
                ->all());
        }

        // The account the campaign is bought on, which is no longer always the
        // configured one.
        //
        // This read "the same one for everybody here", and that was true while
        // a single account was permitted. Once the allow list opened and the
        // buyer could pick between 76 children of the manager, it stopped
        // being true and this went on reading the configured account's
        // conversion actions for every campaign: a stockprices campaign was
        // offered "Purchase" and "Book Demo", which are knowledgedomain's two
        // actions. Picking one would have written a resource name belonging to
        // another account onto the campaign.
        $connection = GoogleAdsConnection::shared();

        if ($connection === null) {
            throw new RuntimeException(GoogleAdsConnection::missingReason());
        }

        $connection = $connection->onCustomer((string) $campaign->ad_account_id);

        return array_map(fn (array $action): array => [
            'id' => $action['resource_name'],
            'name' => $action['name'],
            // The category is what tells a purchase apart from a page view when
            // several actions share a name, which they routinely do.
            'hint' => strtolower(str_replace('_', ' ', $action['category'])),
        ], $this->google->conversionActionOptions($connection));
    }

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

        if (blank($campaign->ad_account_id)) {
            return $this->json(['ok' => false, 'error' => 'Verify the ad account first; pixels are account scoped.']);
        }

        $pixelId = $request->all()['pixel_id'] ?? null;

        try {
            $pixels = $this->candidates($campaign, fresh: filled($pixelId));
        } catch (MetaException|RuntimeException $e) {
            return $this->json(['ok' => false, 'error' => $e->getMessage()]);
        }

        if (blank($pixelId)) {
            $ranked = NameMatch::suggestFirst($pixels, [$campaign->landing_url]);

            $google = $campaign->platform === 'google';

            $this->choices->offer(
                field: $google ? 'conversion_action_resource_name' : 'pixel_id',
                question: $google
                    ? 'Which conversion actions should this campaign count? Pick as many as apply.'
                    : 'Which pixel should conversions be attributed to?',
                options: array_map(fn (array $pixel): array => [
                    'value' => (string) $pixel['id'],
                    'label' => $pixel['name'],
                    'hint' => $pixel['hint'] ?? null,
                    'badge' => ($pixel['suggested'] ?? false) ? 'Suggested' : null,
                    'sends' => $google
                        ? 'Count the '.$pixel['name'].' conversion action'
                        : 'Use pixel '.$pixel['id'],
                ], $ranked),
                // Google counts as many conversion actions as the buyer names,
                // and choose_pixel has always accepted them: pixel_id for the
                // primary, also_count for the rest. Only the question was
                // single-select, so the capability was unreachable by clicking
                // and was reported missing twice. Meta attributes to one pixel,
                // so it stays single.
                multiple: $google,
            );

            return $this->json([
                'ok' => true,
                'pixels' => $pixels,
                'note' => 'The pixels are on screen for the user to pick. Say one short line and wait.',
            ]);
        }

        $chosen = collect($pixels)->firstWhere('id', (string) $pixelId);

        if (! $chosen) {
            return $this->json([
                'ok' => false,
                'error' => $campaign->platform === 'google'
                    ? "Conversion action {$pixelId} is not enabled on this Google Ads account."
                    : "Pixel {$pixelId} is not available on this account or its business.",
                'pixels' => $pixels,
            ]);
        }

        $brandMismatch = $this->brandMismatch($campaign, $chosen);
        $goalMismatch = $this->goalMismatch($campaign, $chosen);
        // Google can optimise toward several categories at once; Meta cannot,
        // so the extra actions are read on Google only and refused elsewhere
        // rather than silently dropped.
        $alsoCount = array_values(array_unique(array_filter(array_map(
            'strval',
            (array) ($request->all()['also_count'] ?? []),
        ))));

        if ($alsoCount !== [] && $campaign->platform !== 'google') {
            return $this->json([
                'ok' => false,
                'error' => 'Counting several conversion events at once is a Google capability. Meta optimises toward one pixel event.',
            ]);
        }

        $unknown = array_values(array_diff($alsoCount, array_column($pixels, 'id')));

        if ($unknown !== []) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('%s is not an enabled conversion action on this account, so nothing was changed.', implode(', ', $unknown)),
                'pixels' => $pixels,
            ]);
        }

        $counted = array_values(array_unique([(string) $pixelId, ...$alsoCount]));

        $campaignMeta = (array) $campaign->meta;
        $metaKey = $campaign->platform === 'google' ? 'conversion_action' : 'pixel';

        if ($campaign->platform === 'google') {
            $campaignMeta['google_conversion_actions'] = $counted;

            // The names as well as the ids, in the order they were chosen.
            // Only the primary's name was kept, so the campaign panel had
            // nothing to show for the others and printed the primary's
            // resource name instead: "all the conversion events are still
            // missing", said of a campaign that had all four at Google.
            $named = collect($pixels)->keyBy('id');
            $campaignMeta['google_conversion_action_names'] = array_values(array_map(
                static fn (string $id): array => [
                    'id' => $id,
                    'name' => (string) ($named[$id]['name'] ?? $id),
                ],
                $counted,
            ));
        }
        $campaignMeta[$metaKey] = array_filter([
            'id' => (string) $chosen['id'],
            'name' => $chosen['name'] ?? null,
            ...$campaign->platform === 'meta' ? [
                'brand_mismatch' => $brandMismatch,
                'goal_mismatch' => $goalMismatch,
            ] : [],
        ], fn (mixed $value): bool => $value !== null && $value !== '');

        $campaign->update(['pixel_id' => $chosen['id'], 'meta' => $campaignMeta]);
        $this->workspace->recordSource($campaign, 'pixel_id', ArtifactFieldSource::PLATFORM_RETURNED);

        return $this->json(array_filter([
            'ok' => true,
            'pixel_id' => $chosen['id'],
            'name' => $chosen['name'] ?? null,
            // The whole set, so the model confirms what was recorded rather
            // than naming the primary and leaving the buyer to guess whether
            // the others took. It said "the Purchase conversion action is
            // selected" for a campaign counting three.
            'conversion_actions' => $campaign->platform === 'google' ? $counted : null,
            'brand_mismatch' => $brandMismatch,
            'goal_mismatch' => $goalMismatch,
            'note' => $brandMismatch || $goalMismatch
                ? 'Say what is off and ask them to confirm before publishing. Do not change it yourself.'
                : (count($counted) > 1
                    ? 'Name every conversion action that is now counted, not just the first.'
                    : null),
        ], fn (mixed $value): bool => $value !== null));
    }

    /**
     * A pixel belonging to a different brand, said out loud.
     *
     * The same check ChoosePage makes, for the same reason and with the same
     * words. On arb-dev an AttestPath campaign was given the StockPrices pixel
     * and the reply only named it: the Page mismatch two turns earlier got
     * "please confirm that's intentional" and this got nothing. A pixel decides
     * which conversions are attributed and to whom, so it is the more expensive
     * of the two to get wrong.
     *
     * Reported rather than refused. One business legitimately runs several
     * brands through one pixel, and only the buyer knows whether this is that.
     *
     * @param  array<string, mixed>  $chosen
     */
    private function brandMismatch(Campaign $campaign, array $chosen): ?string
    {
        $name = trim((string) ($chosen['name'] ?? ''));
        $brand = NameMatch::words([$campaign->landing_url]);

        if ($name === '' || $brand === [] || NameMatch::matches($name, $brand)) {
            return null;
        }

        return sprintf(
            '%s does not match %s. Conversions would be attributed to it rather than to the advertised site.',
            $name,
            parse_url((string) $campaign->landing_url, PHP_URL_HOST) ?: $campaign->landing_url,
        );
    }

    /**
     * A conversion that is not the one the campaign is optimising for.
     *
     * Seen on arb-dev: objective LEADS, conversion action Purchase, and nothing
     * said a word. The campaign then buys the wrong outcome at full price and
     * reports it as underdelivery, which is the hardest kind of mistake to
     * trace back because every number looks plausible.
     *
     * Matched on the action's own name rather than a platform enum, because
     * these are advertiser-defined on both Meta and Google and the name is the
     * only thing either end agrees on.
     *
     * @param  array<string, mixed>  $chosen
     */
    private function goalMismatch(Campaign $campaign, array $chosen): ?string
    {
        $expected = match (true) {
            str_contains((string) $campaign->objective, 'LEAD') => ['lead', 'form', 'signup', 'sign up', 'contact', 'enquiry', 'inquiry', 'submit'],
            str_contains((string) $campaign->objective, 'SALE') => ['purchase', 'sale', 'checkout', 'order', 'transaction'],
            default => [],
        };

        $name = strtolower(trim((string) ($chosen['name'] ?? '')));

        if ($expected === [] || $name === '' || NameMatch::matches($name, $expected)) {
            return null;
        }

        return sprintf(
            'This campaign optimises for %s, and %s does not read like that kind of conversion.',
            str_contains((string) $campaign->objective, 'LEAD') ? 'leads' : 'sales',
            $chosen['name'],
        );
    }
}
