<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\MetaPromotedConversion;
use App\Campaigns\Objectives;
use App\Models\ArtifactFieldSource;
use App\Models\Campaign;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaException;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;

/**
 * Which pixel event the ad set optimises toward.
 *
 * This was never asked. The event came from the objective alone: leads meant
 * LEAD, sales meant PURCHASE, and whether the pixel had ever fired such an event
 * was not consulted. Meta accepts it either way and the campaign then spends
 * against something it can never observe, so delivery reads as underdelivery and
 * every number on the report looks plausible. It is the hardest kind of mistake
 * to trace, which is why it is asked rather than inferred.
 *
 * Kaushal's campaign 120252047635070626 is the live example: pixel
 * 1017787001151608 fires PageView and Subscribe, 102 and 1 times, and has never
 * once fired Lead, which is what the ad set is asking Meta to optimise toward.
 *
 * The pixel's own history is the list, because it is the only evidence of what
 * the site actually sends. The objective's default is still offered and still
 * marked, so the ordinary case stays one click, but an event the pixel has never
 * fired says so rather than being presented as the obvious choice.
 */
class ChooseConversionEvent implements Tool
{
    use ActsOnFocusedCampaign;

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

    public function description(): Stringable|string
    {
        return 'Offer the conversion events this objective can optimise toward. The list is the standard '
            .'events, the custom events this pixel has fired, and the custom conversions on the ad account, '
            .'with what has fired marked on each. Set the chosen one by passing conversion_event. A custom '
            .'event publishes as OTHER with its name. A custom conversion publishes by its id. An event the '
            .'pixel has not fired yet is allowed and warned about, not refused. Meta only, and only for '
            .'objectives that optimise toward a pixel event. Call this after choose_pixel.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'conversion_event' => $schema->string()
                ->description('The pixel event name as Meta reports it, such as Purchase, Lead or Subscribe.'),
        ];
    }

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

        if ($campaign->platform !== 'meta') {
            return $this->json([
                'ok' => false,
                'error' => sprintf(
                    'Optimising toward a pixel event is a Meta setting and this campaign is on %s.',
                    $campaign->platform,
                ),
            ]);
        }

        // No pixel event to optimise toward on a traffic or awareness campaign:
        // the ad set promotes the Page, and sending custom_event_type against it
        // is rejected by Meta rather than ignored.
        if (Objectives::conversionEvent($campaign->objective) === null) {
            return $this->json([
                'ok' => false,
                'error' => sprintf(
                    'The %s objective does not optimise toward a pixel event, so there is nothing to choose here.',
                    $campaign->objective ?? 'selected',
                ),
                'note' => 'Do not ask the user about this. Move on to the next step.',
            ]);
        }

        if (blank($campaign->pixel_id)) {
            return $this->json([
                'ok' => false,
                'error' => 'Choose the pixel first. The events on offer are the ones that pixel has been firing.',
            ]);
        }

        $default = Objectives::conversionEvent($campaign->objective);
        $defaultName = Objectives::eventName($default);

        try {
            $fired = $this->meta->pixelEvents($campaign->pixel_id);
        } catch (MetaException $e) {
            return $this->json(['ok' => false, 'error' => $e->getMessage()]);
        }

        $conversions = $this->customConversions($campaign);
        $arguments = $request->all();

        if (! array_key_exists('conversion_event', $arguments)) {
            return $this->offer($campaign, $fired, $conversions, $defaultName);
        }

        $chosen = trim((string) $arguments['conversion_event']);

        if ($chosen === '') {
            return $this->json([
                'ok' => false,
                'error' => 'Name the event, or leave it unset to keep the objective\'s default.',
            ]);
        }

        $conversion = $this->matchedConversion($chosen, $conversions);

        if ($conversion !== null) {
            $campaign->update([
                'conversion_event' => MetaPromotedConversion::storedCustomConversion($conversion['id']),
            ]);
            $this->workspace->recordSource($campaign, 'conversion_event', ArtifactFieldSource::USER_STATED);

            return $this->json([
                'ok' => true,
                'conversion_event' => MetaPromotedConversion::storedCustomConversion($conversion['id']),
                'event_name' => $conversion['name'],
                'note' => sprintf('%s is a custom conversion, so it is published by its id.', $conversion['name']),
            ]);
        }

        $customName = $this->matchedCustomEvent($chosen, $fired);

        if ($customName !== null) {
            if (! Objectives::acceptsEventType($campaign->objective, 'OTHER')) {
                return $this->json([
                    'ok' => false,
                    'error' => sprintf(
                        '%s cannot be optimised toward on a %s campaign.%s',
                        $customName,
                        Objectives::label($campaign->objective),
                        $this->acceptedClause($campaign->objective),
                    ),
                    'accepted' => Objectives::acceptedEventTypes($campaign->objective),
                    'note' => 'Call this tool again with no arguments to put the events this objective does accept '
                        .'on screen, and let the user pick. Do not pick one for them, and do not suggest changing '
                        .'pixel or objective: the only thing refused here is this one event.',
                ]);
            }

            $campaign->update([
                'conversion_event' => MetaPromotedConversion::storedCustomEvent($customName),
            ]);
            $this->workspace->recordSource($campaign, 'conversion_event', ArtifactFieldSource::USER_STATED);

            $times = $this->firedCount($fired, $customName);

            return $this->json(array_filter([
                'ok' => true,
                'conversion_event' => 'OTHER',
                'event_name' => $customName,
                'custom_event_str' => $customName,
                'times_fired' => $times,
                'warning' => $times === 0
                    ? sprintf(
                        '%s has not fired on this pixel yet, so Meta has no conversions to optimise against and '
                        .'delivery will be poor until it does. The campaign can still be published.',
                        $customName,
                    )
                    : null,
                'note' => sprintf('%s is a custom event, so it is published as OTHER with that name. Say that in one line.', $customName),
            ], fn ($v) => $v !== null));
        }

        // Matched case-insensitively against the pixel's own history first, then
        // against Meta's standard names, so "lead" becomes "Lead" either way.
        //
        // What is deliberately not here any more: a refusal when the pixel has
        // not fired the chosen event. That read "This pixel has not fired Lead.
        // It has fired: PageView." and it was the blocker. A pixel's history is
        // evidence about delivery, not permission - Meta accepts an event with no
        // history and simply has nothing to optimise on yet. Refusing it meant a
        // leads campaign on a PageView-only pixel had no selectable answer at
        // all, and every way the buyer tried to say "use Lead anyway" was turned
        // down. The warning below replaces it.
        $matched = collect(array_keys($fired))
            ->map(fn (string $name): ?string => Objectives::canonicalEventName($name))
            ->filter()
            ->first(fn (string $name): bool => strcasecmp($name, $chosen) === 0)
            ?? collect(Objectives::selectableEventNames($campaign->objective))
                ->first(fn (string $name): bool => strcasecmp($name, $chosen) === 0)
            ?? Objectives::canonicalEventName($chosen);

        if ($matched === null) {
            return $this->json([
                'ok' => false,
                'error' => 'Name a standard event, a custom event this pixel has fired, or a custom conversion from the list.',
            ]);
        }

        $name = $matched;
        $type = Objectives::eventType($name);

        // The pixel having fired it is not enough. A sales ad set takes eight
        // event types and refuses the rest, so an event this pixel really does
        // fire can still be one Meta will not optimise toward - which is how
        // PageView reached ads_create_ad_set on production and was refused after
        // the campaign object already existed.
        if (! Objectives::acceptsEventType($campaign->objective, $type)) {
            return $this->json([
                'ok' => false,
                'error' => sprintf(
                    '%s cannot be optimised toward on a %s campaign.%s',
                    $name,
                    Objectives::label($campaign->objective),
                    $this->acceptedClause($campaign->objective),
                ),
                'accepted' => Objectives::acceptedEventTypes($campaign->objective),
                'note' => 'Call this tool again with no arguments to put the events this objective does accept '
                    .'on screen, and let the user pick. Do not pick one for them, and do not suggest changing '
                    .'pixel or objective: the only thing refused here is this one event.',
            ]);
        }

        $campaign->update(['conversion_event' => $type]);
        $this->workspace->recordSource($campaign, 'conversion_event', ArtifactFieldSource::USER_STATED);

        $times = $this->firedCount($fired, $name);

        return $this->json(array_filter([
            'ok' => true,
            'conversion_event' => $type,
            'event_name' => $name,
            'times_fired' => $times,
            // Said once, plainly, instead of refused. Meta takes the event; what
            // it does not have is anything to learn from, so delivery is the
            // thing at risk and the buyer is the one who gets to weigh that.
            'warning' => $times === 0
                ? sprintf(
                    '%s has not fired on this pixel yet, so Meta has no conversions to optimise against and '
                    .'delivery will be poor until it does. The campaign can still be published.',
                    $name,
                )
                : null,
            // OTHER is not a fallback here, it is the enum for anything outside
            // Meta's own list, and a buyer should know the event is being
            // published that way.
            'note' => $type === 'OTHER'
                ? sprintf('%s is a custom event, so it is published as OTHER. Say that in one line.', $name)
                : null,
        ], fn ($v) => $v !== null));
    }

    /**
     * Standard events, custom events the pixel has fired, and custom conversions.
     *
     * Fired rows come first. The objective's own event stays suggested when the
     * pixel has fired it. When it has not, the suggestion moves to the event
     * that has fired the most, so Purchase is not the default on a pixel that
     * has only recorded Lead.
     *
     * @param  array<string, int>  $fired
     * @param  list<array{id: string, name: string, custom_event_type: ?string, pixel_id: ?string, last_fired_time: ?string}>  $conversions
     */
    private function offer(Campaign $campaign, array $fired, array $conversions, ?string $defaultName): Stringable|string
    {
        $selectable = Objectives::selectableEventNames($campaign->objective);
        $options = [];
        $order = 0;

        foreach ($selectable as $name) {
            $count = $this->firedCount($fired, $name);
            $options[] = $this->eventOption($name, $name, $count, $count > 0, $order++);
        }

        if (Objectives::acceptsEventType($campaign->objective, 'OTHER')) {
            foreach ($fired as $name => $count) {
                $name = (string) $name;

                if ($count < 1 || Objectives::canonicalEventName($name) !== null || ! MetaPromotedConversion::isCustomEventName($name)) {
                    continue;
                }

                $options[] = $this->eventOption(
                    MetaPromotedConversion::storedCustomEvent($name),
                    $name,
                    (int) $count,
                    true,
                    $order++,
                );
            }
        }

        foreach ($conversions as $conversion) {
            $active = filled($conversion['last_fired_time']);
            $options[] = [
                'value' => MetaPromotedConversion::storedCustomConversion($conversion['id']),
                'label' => $conversion['name'],
                'hint' => $active ? 'Custom conversion' : 'Custom conversion, not fired yet',
                'sends' => 'Optimise toward '.$conversion['name'],
                'count' => 0,
                'active' => $active,
                'order' => $order++,
            ];
        }

        usort($options, function (array $left, array $right): int {
            if ($left['active'] !== $right['active']) {
                return $left['active'] ? -1 : 1;
            }

            if ($left['active'] && $left['count'] !== $right['count']) {
                return $right['count'] <=> $left['count'];
            }

            return $left['order'] <=> $right['order'];
        });

        $defaultCount = $defaultName !== null ? $this->firedCount($fired, $defaultName) : 0;
        $busiest = collect($options)->first(fn (array $option): bool => $option['active'] && $option['count'] > 0);
        $suggested = $defaultCount > 0
            ? $defaultName
            : (is_array($busiest) ? $busiest['value'] : $defaultName);

        $this->choices->offer(
            field: 'conversion_event',
            question: 'Which event should this campaign optimise toward?',
            options: array_map(fn (array $option): array => [
                'value' => $option['value'],
                'label' => $option['label'],
                'hint' => $option['hint'],
                'badge' => $option['value'] === $suggested ? 'Suggested' : null,
                'sends' => $option['sends'],
            ], $options),
            allowOther: true,
        );

        $defaultNeverFired = $defaultName !== null && $defaultCount === 0;

        return $this->json(array_filter([
            'ok' => true,
            'events' => $fired,
            'selectable' => $selectable,
            'default' => $defaultName,
            'default_never_fired' => $defaultNeverFired ?: null,
            'note' => $defaultNeverFired
                ? sprintf(
                    'Say this before anything else: the %s objective would optimise toward %s, and this pixel has '
                    .'never fired that event, so the campaign would be buying something it cannot measure. The '
                    .'events on screen include the standard events, the custom events this pixel has fired, and '
                    .'any custom conversions. What the pixel has fired is marked on each. Then wait.',
                    $campaign->objective,
                    $defaultName,
                )
                : 'The events are on screen for the user to pick. Say one short line and wait.',
        ], fn ($v) => $v !== null));
    }

    /**
     * @return array{value: string, label: string, hint: string, sends: string, count: int, active: bool, order: int}
     */
    private function eventOption(string $value, string $label, int $count, bool $active, int $order): array
    {
        return [
            'value' => $value,
            'label' => $label,
            'hint' => $count > 0
                ? sprintf('fired %s %s', number_format($count), $count === 1 ? 'time' : 'times')
                : 'not fired on this pixel yet',
            'sends' => 'Optimise toward '.$label,
            'count' => $count,
            'active' => $active,
            'order' => $order,
        ];
    }

    /**
     * Custom conversions are optional. A failure leaves the pixel's own events on screen.
     *
     * @return list<array{id: string, name: string, custom_event_type: ?string, pixel_id: ?string, last_fired_time: ?string}>
     */
    private function customConversions(Campaign $campaign): array
    {
        if (blank($campaign->ad_account_id)) {
            return [];
        }

        try {
            return $this->meta->customConversions((string) $campaign->ad_account_id, (string) $campaign->pixel_id);
        } catch (MetaException $exception) {
            logger()->warning('Custom conversions could not be read', [
                'pixel_id' => $campaign->pixel_id,
                'exception' => $exception->getMessage(),
            ]);

            return [];
        }
    }

    /**
     * @param  list<array{id: string, name: string, custom_event_type: ?string, pixel_id: ?string, last_fired_time: ?string}>  $conversions
     * @return array{id: string, name: string, custom_event_type: ?string, pixel_id: ?string, last_fired_time: ?string}|null
     */
    private function matchedConversion(string $chosen, array $conversions): ?array
    {
        $id = str_starts_with($chosen, 'conversion:')
            ? MetaPromotedConversion::customConversionId($chosen)
            : null;

        if ($id !== null) {
            return collect($conversions)->first(fn (array $conversion): bool => $conversion['id'] === $id);
        }

        return null;
    }

    /**
     * @param  array<string, int>  $fired
     */
    private function matchedCustomEvent(string $chosen, array $fired): ?string
    {
        $name = str_starts_with($chosen, 'event:') ? substr($chosen, strlen('event:')) : $chosen;

        if (! MetaPromotedConversion::isCustomEventName($name) || Objectives::canonicalEventName($name) !== null) {
            return null;
        }

        $fromHistory = collect(array_keys($fired))
            ->first(fn (string $firedName): bool => strcasecmp($firedName, $name) === 0 && MetaPromotedConversion::isCustomEventName($firedName));

        return $fromHistory ?? $name;
    }

    /**
     * @param  array<string, int>  $fired
     */
    private function firedCount(array $fired, string $name): int
    {
        if (array_key_exists($name, $fired)) {
            return (int) $fired[$name];
        }

        foreach ($fired as $firedName => $count) {
            if (strcasecmp((string) $firedName, $name) === 0) {
                return (int) $count;
            }
        }

        return 0;
    }

    /**
     * The accepted events in pixel vocabulary, for saying to a person.
     *
     * The enum is Meta's internal spelling. A buyer looking at Events Manager
     * sees ViewContent, not CONTENT_VIEW, and telling them the enum sends them
     * looking for something that is not on their screen.
     */
    private function acceptedNames(?string $objective): string
    {
        $accepted = Objectives::acceptedEventTypes($objective) ?? [];

        return collect($accepted)
            ->map(fn (string $type): string => Objectives::eventName($type) ?? $type)
            ->implode(', ');
    }

    /**
     * That list as a sentence, or nothing when we do not hold one.
     *
     * Only OUTCOME_SALES has a known list, so every other objective rendered
     * "Meta accepts  there." with the names missing and the gap left in. It had
     * never shown before because the only refusal that could reach it was a
     * sales one; refusing PAGE_VIEW on every objective is what brought the other
     * four into the same sentence.
     *
     * Dropped rather than filled, because what Meta does accept on a leads or
     * traffic campaign is exactly the thing nobody has told us. The two ways out
     * are in the note either way, and they are what the buyer needs.
     */
    private function acceptedClause(?string $objective): string
    {
        $names = $this->acceptedNames($objective);

        return $names === '' ? '' : sprintf(' Meta accepts %s there.', $names);
    }
}
