<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\BudgetCeiling;
use App\Campaigns\CampaignApprovalBinding;
use App\Campaigns\CreatedIds;
use App\Campaigns\PendingChanges;
use App\Campaigns\Platforms\LinkedInRules;
use App\Campaigns\Publishing\LinkedInPublisher;
use App\Models\Campaign;
use App\Models\CampaignChange;
use App\Services\LinkedIn\LinkedIn;
use App\Services\LinkedIn\LinkedInTargetingFacets;
use App\Services\LinkedIn\LinkedInUrn;
use App\Support\Actor;
use Carbon\Carbon;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Approvals\Approval;
use Laravel\Ai\Concerns\InteractsWithApprovals;
use Laravel\Ai\Contracts\Approvable;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;
use Throwable;

/**
 * Budget, bidding, target cost, end date, placements, and locations on a live LinkedIn campaign.
 *
 * Meta has its own editor. This one refuses every other platform, and it
 * refuses the LinkedIn fields that are fixed once the campaign exists.
 */
class EditLinkedInCampaign implements Approvable, Tool
{
    use ActsOnFocusedCampaign, InteractsWithApprovals;

    /** @var list<string> */
    private const FIELDS = ['name', 'budget', 'bid_strategy', 'bid_amount', 'ends_at', 'continuous', 'placements', 'location_query', 'keep_locations', 'locations', 'audience', 'audience_facet', 'audience_query', 'audience_include', 'audience_exclude', 'audience_expansion', 'matched_audiences', 'matched_operation'];

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Choices $choices,
        private readonly CampaignApprovalBinding $approvalBinding,
        private readonly PendingChanges $pending,
        private readonly Actor $actor,
        private readonly LinkedInRules $rules,
    ) {}

    public function name(): string
    {
        return 'edit_linkedin_campaign';
    }

    public function description(): Stringable|string
    {
        return 'Change the ad set name, daily budget, bidding, target cost, end date, placements, or locations on a LinkedIn campaign '
            .'that is already live. The ad set name is the campaign name LinkedIn shows. Call it with no '
            .'arguments to offer those choices. Pass name as the new ad set name. Pass placements as an empty '
            .'list to offer LinkedIn feed and Audience Network, and both can be selected. Pass location_query '
            .'to search LinkedIn places and let the user pick more than one. A later search in that same list '
            .'stays on the list. Do not call this again for it, and do not offer a second list. '
            .'Pass locations as the chosen urn:li:geo ids. That replaces the location list and keeps the rest of the audience. Pass audience as an empty '
            .'list to change audience attributes, matched audiences, or Audience Expansion. A running campaign cannot '
            .'move its start. Pass continuous to remove the end date. Do not use this for Meta, and do not '
            .'use it to change the objective, landing page, click tracking, ad account, '
            .'Page, or campaign group.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'name' => $schema->string()->description('The new ad set name. This is the campaign name LinkedIn shows. 1 to 200 bytes once the ARB- prefix is included.'),
            'budget' => $schema->number()->description('The new budget amount in the account currency. The daily or lifetime arrangement stays as it is.'),
            'bid_strategy' => $schema->string()->description('AUTOMATED_BID, TARGET_COST, or MAXIMUM_BID.'),
            'bid_amount' => $schema->number()->description('The target cost or maximum bid. Required for those two. Leave it out for automated bidding.'),
            'ends_at' => $schema->string()->description('When the campaign should stop, as a date. Do not send a new start.'),
            'continuous' => $schema->boolean()->description('True removes the end date so the campaign runs until it is stopped.'),
            'placements' => $schema->array()->items($schema->string())->description('linkedin_feed, linkedin_audience_network, or both. Pass an empty list to show those two choices. Both can be selected.'),
            'location_query' => $schema->string()->description('A place to search on LinkedIn, such as new york. Shows the matches. Does not send a change by itself.'),
            'keep_locations' => $schema->array()->items($schema->string())->description('urn:li:geo ids already chosen. Pass with location_query so the next list keeps them selected and adds the new matches. Does not send a change by itself.'),
            'locations' => $schema->array()->items($schema->string())->description('urn:li:geo ids chosen from the LinkedIn search. More than one is allowed. This replaces the current locations.'),
            'audience' => $schema->array()->items($schema->string())->description('Pass an empty list to offer LinkedIn audience attributes, matched audiences, and Audience Expansion.'),
            'audience_facet' => $schema->string()->description('A LinkedIn audience attribute from the menu, such as titles, jobFunctions, degrees, fieldsOfStudy, schools, interests, or groups.'),
            'audience_query' => $schema->string()->description('Search text for a LinkedIn job title, industry, skill, or company. Does not send a change by itself.'),
            'audience_include' => $schema->array()->items($schema->string())->description('URNs chosen from the current LinkedIn attribute search.'),
            'audience_exclude' => $schema->boolean()->description('True excludes the chosen attribute URNs instead of including them.'),
            'audience_expansion' => $schema->boolean()->description('True enables LinkedIn Audience Expansion. False turns it off.'),
            'matched_audiences' => $schema->array()->items($schema->string())->description('urn:li:adSegment ids. Pass an empty list to show the account matched audiences.'),
            'matched_operation' => $schema->string()->description('include or exclude, for the matched audiences being saved. Defaults to include.'),
        ];
    }

    protected function needsApproval(Request $request): Approval|bool
    {
        $campaign = $this->focused();
        $given = $this->given($request);

        unset($given['location_query'], $given['keep_locations'], $given['audience_query'], $given['matched_operation']);

        if (array_key_exists('audience', $given) && $given['audience'] === []) {
            unset($given['audience']);
        }

        if (array_key_exists('matched_audiences', $given) && $given['matched_audiences'] === []) {
            unset($given['matched_audiences']);
        }

        if (! array_key_exists('audience_include', $given)) {
            unset($given['audience_facet'], $given['audience_exclude']);
        }

        if (array_key_exists('placements', $given) && $given['placements'] === []) {
            unset($given['placements']);
        }

        if (array_key_exists('locations', $given) && $given['locations'] === []) {
            unset($given['locations']);
        }

        if ($campaign === null || $campaign->platform !== 'linkedin' || ! $campaign->isPublished() || $given === []) {
            return false;
        }

        return $this->approvalBinding->request(
            $request,
            $campaign,
            'edit_linkedin_campaign',
            note: 'This changes the live LinkedIn campaign.',
        );
    }

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

        if ($campaign === null) {
            return $this->noCampaign();
        }

        if ($campaign->platform !== 'linkedin') {
            return $this->json([
                'ok' => false,
                'error' => 'This editor is only for a LinkedIn campaign. Leave the Meta campaign on its own editor.',
            ]);
        }

        if (! $campaign->isPublished()) {
            return $this->json([
                'ok' => false,
                'error' => 'This LinkedIn campaign is still a draft. Set its budget, bidding, and schedule on the draft.',
            ]);
        }

        $this->usePanelAdSet($campaign);

        $unknown = array_diff(array_keys($this->present($request)), self::FIELDS);

        if ($unknown !== []) {
            return $this->json([
                'ok' => false,
                'error' => sprintf('%s cannot be changed after this campaign is on LinkedIn.', implode(', ', $unknown)),
                'note' => 'Say that plainly. Do not try a Meta tool.',
            ]);
        }

        $given = $this->given($request);

        if (array_key_exists('location_query', $given)) {
            if (array_diff(array_keys($given), ['location_query', 'keep_locations']) !== []) {
                return $this->json([
                    'ok' => false,
                    'error' => 'Search LinkedIn locations on their own, then pick from the matches.',
                    'note' => 'Nothing was sent to LinkedIn.',
                ]);
            }

            return $this->searchLocations(
                $campaign,
                (string) $given['location_query'],
                array_values(array_filter((array) ($given['keep_locations'] ?? []), 'is_string')),
            );
        }

        unset($given['keep_locations']);

        if (array_key_exists('audience', $given) && $given['audience'] === [] && count($given) === 1) {
            $this->offerAudience();

            return $this->json([
                'ok' => true,
                'note' => 'The LinkedIn audience choices are on screen. Wait for a choice. Nothing has been sent.',
            ]);
        }

        if (array_key_exists('matched_audiences', $given) && $given['matched_audiences'] === [] && ! array_key_exists('audience_include', $given) && ! array_key_exists('audience_expansion', $given)) {
            return $this->offerMatchedAudiences($campaign, (string) ($given['matched_operation'] ?? 'include'));
        }

        if ((bool) ($given['audience_exclude'] ?? false) && ! array_key_exists('audience_facet', $given) && ! array_key_exists('audience_include', $given)) {
            return $this->searchAudience($campaign, '', null, true);
        }

        if (array_key_exists('audience_facet', $given) && ! array_key_exists('audience_include', $given)) {
            return $this->searchAudience($campaign, (string) $given['audience_facet'], isset($given['audience_query']) ? (string) $given['audience_query'] : null, (bool) ($given['audience_exclude'] ?? false));
        }

        if (array_key_exists('locations', $given) && $given['locations'] === []) {
            return $this->json([
                'ok' => false,
                'error' => 'Pick at least one LinkedIn place from the search.',
                'note' => 'Nothing was sent to LinkedIn.',
            ]);
        }

        if (array_key_exists('placements', $given) && $given['placements'] === []) {
            unset($given['placements']);

            if ($given === []) {
                $this->offerPlacements();

                return $this->json([
                    'ok' => true,
                    'note' => 'Both LinkedIn placements are on screen. Wait for the selection. Nothing has been sent.',
                ]);
            }
        }

        if ($given === []) {
            $this->offer();

            return $this->json([
                'ok' => true,
                'note' => 'The buttons are the LinkedIn fields that can change. Wait for a choice. Nothing has been sent.',
            ]);
        }

        $refusal = $this->refusal($campaign, $given);

        if ($refusal !== null) {
            return $this->json(['ok' => false, 'error' => $refusal, 'note' => 'Nothing was sent to LinkedIn.']);
        }

        $before = [
            'name' => $campaign->name,
            'budget' => $campaign->budget,
            'bid_strategy' => $campaign->bid_strategy,
            'bid_amount' => $campaign->bid_amount,
            'ends_at' => $campaign->ends_at,
            'placements' => $campaign->placements,
            'locations' => $campaign->locations,
            'audience' => $campaign->audience,
            'meta' => $campaign->meta,
        ];
        $places = null;

        if (array_key_exists('locations', $given)) {
            $places = $this->confirmedPlaces($campaign, $given['locations']);

            if (is_string($places)) {
                return $this->json([
                    'ok' => false,
                    'error' => $places,
                    'note' => 'Nothing was sent to LinkedIn.',
                ]);
            }
        }

        $audience = null;

        if (array_key_exists('audience_include', $given)) {
            $audience = $this->confirmedAttributes($campaign, (string) ($given['audience_facet'] ?? ''), (array) $given['audience_include'], (bool) ($given['audience_exclude'] ?? false));

            if (is_string($audience)) {
                return $this->json(['ok' => false, 'error' => $audience, 'note' => 'Nothing was sent to LinkedIn.']);
            }
        }

        if (array_key_exists('matched_audiences', $given) && $given['matched_audiences'] !== []) {
            $matched = $this->confirmedMatched($campaign, (array) $given['matched_audiences'], (string) ($given['matched_operation'] ?? 'include'));

            if (is_string($matched)) {
                return $this->json(['ok' => false, 'error' => $matched, 'note' => 'Nothing was sent to LinkedIn.']);
            }

            $audience = $this->withMatched($audience ?? (array) ($campaign->audience ?? []), $matched);
        }

        $stored = $this->stored($given, $places);

        if ($audience !== null) {
            $stored['audience'] = $audience;
        }

        if (array_key_exists('audience_expansion', $given)) {
            $stored['meta'] = [...(array) ($campaign->meta ?? []), 'linkedin_audience_expansion' => (bool) $given['audience_expansion']];
        }

        $changes = [];

        foreach ($stored as $field => $value) {
            if ($field === 'meta') {
                $next = (bool) ($value['linkedin_audience_expansion'] ?? false);
                $previous = (bool) (($before['meta']['linkedin_audience_expansion'] ?? false));

                if ($next !== $previous) {
                    $changes['audience_expansion'] = ['from' => $previous, 'to' => $next];
                }

                continue;
            }

            $from = match ($field) {
                'name' => preg_replace('/^ARB-/', '', (string) $before['name']),
                'placements' => $this->chosenPlacements($before['placements']),
                default => $before[$field],
            };

            if ($from == $value) {
                continue;
            }

            $changes[$field] = ['from' => $from, 'to' => $value];
        }

        if ($changes === []) {
            return $this->json([
                'ok' => false,
                'error' => 'That is already the value on this LinkedIn campaign.',
                'note' => 'Nothing was sent.',
            ]);
        }

        $campaign->forceFill($stored)->save();

        try {
            $live = $campaign->fresh();
            $this->usePanelAdSet($live);
            app(LinkedInPublisher::class)->update($live, $changes, $this->actor->describe());
        } catch (Throwable $exception) {
            $campaign->forceFill($before)->save();
            $campaign->update(['last_error' => $exception->getMessage()]);
            CampaignChange::create([
                'campaign_id' => $campaign->id,
                'actor' => $this->actor->describe(),
                'changes' => $changes,
                'state' => 'failed',
                'error' => $exception->getMessage(),
            ]);

            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'LinkedIn did not take the change. The campaign here was put back.',
            ]);
        }

        $fresh = $campaign->fresh();
        $fresh->update([
            'published_state' => $this->pending->snapshot($fresh),
            'last_synced_at' => now(),
            'last_error' => null,
        ]);
        CampaignChange::create([
            'campaign_id' => $fresh->id,
            'actor' => $this->actor->describe(),
            'changes' => $changes,
            'state' => 'applied',
            'applied_at' => now(),
        ]);

        return $this->json([
            'ok' => true,
            'applied' => $changes,
            'note' => 'The live LinkedIn campaign now has this change. Do not call push_changes for it.',
        ]);
    }

    /**
     * The panel's Ad set id is the LinkedIn campaign this edit is sent to.
     *
     * Marked unchanged so a later save of the name or budget does not rewrite
     * the stored external id.
     */
    private function usePanelAdSet(Campaign $campaign): void
    {
        $adSetId = CreatedIds::linkedinPanel($campaign)['ad_set_id'];

        if ($adSetId === null) {
            return;
        }

        $campaign->external_campaign_id = $adSetId;
        $campaign->syncOriginalAttribute('external_campaign_id');
    }

    /** @param array<string, mixed> $payload */
    protected function json(array $payload): string
    {
        $campaign = $this->focused();

        if ($campaign instanceof Campaign && $campaign->platform === 'linkedin') {
            $payload['panel'] = CreatedIds::linkedinPanel($campaign);
            $payload['panel_note'] = 'These are the ids on the right-hand panel. The Campaign id is the campaign group. The Ad set id is the LinkedIn campaign this edit uses. When the user did not name another id, quote these two and no other LinkedIn id.';
        }

        return json_encode($payload, JSON_UNESCAPED_SLASHES);
    }

    private function offer(): void
    {
        $this->choices->offer(
            'linkedin_edit',
            'What should change on this LinkedIn campaign?',
            [
                [
                    'value' => 'name',
                    'label' => 'Ad set name',
                    'hint' => 'The campaign name LinkedIn shows.',
                    'sends' => 'Change the LinkedIn ad set name. Ask for the new name if I have not given one, then call edit_linkedin_campaign with name.',
                ],
                [
                    'value' => 'budget',
                    'label' => 'Daily budget',
                    'hint' => 'The amount only. Daily or lifetime stays as it is.',
                    'sends' => 'Change the LinkedIn budget. Ask the amount if I have not given one, then call edit_linkedin_campaign.',
                ],
                [
                    'value' => 'bidding',
                    'label' => 'Bidding',
                    'hint' => 'Automated, target cost, or maximum bid.',
                    'sends' => 'Change the LinkedIn bidding. Call edit_linkedin_campaign with the bid strategy.',
                ],
                [
                    'value' => 'target_cost',
                    'label' => 'Target cost',
                    'hint' => 'The number for target cost or maximum bid.',
                    'sends' => 'Change the LinkedIn target cost. Ask the number if I have not given one, then call edit_linkedin_campaign.',
                ],
                [
                    'value' => 'schedule',
                    'label' => 'Schedule',
                    'hint' => 'The end date. The start cannot move.',
                    'sends' => 'Change the LinkedIn end date. Ask when it should stop, or whether it should run continuously. Call edit_linkedin_campaign. Do not move the start.',
                ],
                [
                    'value' => 'placements',
                    'label' => 'Placements',
                    'hint' => 'LinkedIn feed and Audience Network. Both can be selected.',
                    'sends' => 'Change the LinkedIn placements. Call edit_linkedin_campaign with placements as an empty list so LinkedIn feed and Audience Network can both be picked.',
                ],
                [
                    'value' => 'locations',
                    'label' => 'Locations',
                    'hint' => 'Search LinkedIn and pick one or more places.',
                    'sends' => 'Change the LinkedIn locations. Ask which place to search if I have not named one, then call edit_linkedin_campaign with location_query.',
                ],
                [
                    'value' => 'audience',
                    'label' => 'Target audience',
                    'hint' => 'Job title, industry, skills, matched audiences, or Audience Expansion.',
                    'sends' => 'Change the LinkedIn target audience. Call edit_linkedin_campaign with audience as an empty list.',
                ],
            ],
        );
    }

    private function offerPlacements(): void
    {
        $this->choices->offer(
            'linkedin_placements',
            'Which LinkedIn placements should this campaign use?',
            [
                [
                    'value' => 'linkedin_feed',
                    'label' => 'LinkedIn feed',
                    'hint' => 'Ads in the LinkedIn feed.',
                    'sends' => 'linkedin_feed',
                ],
                [
                    'value' => 'linkedin_audience_network',
                    'label' => 'Audience Network',
                    'hint' => 'Also deliver off LinkedIn. Select this with the feed, or on its own.',
                    'sends' => 'linkedin_audience_network',
                ],
            ],
            multiple: true,
        );
    }

    /**
     * @param  list<string>  $keep
     */
    private function searchLocations(Campaign $campaign, string $query, array $keep = []): string
    {
        $query = trim($query);

        if (mb_strlen($query) < 2 || mb_strlen($query) > 80) {
            return $this->json([
                'ok' => false,
                'error' => 'Search LinkedIn locations with 2 to 80 characters.',
                'note' => 'Nothing was sent to LinkedIn.',
            ]);
        }

        $kept = [];

        if ($keep !== []) {
            $confirmed = $this->confirmedPlaces($campaign, $keep);

            if (is_string($confirmed)) {
                return $this->json([
                    'ok' => false,
                    'error' => $confirmed,
                    'note' => 'Nothing was sent to LinkedIn.',
                ]);
            }

            $kept = $confirmed;
        }

        try {
            $matches = app(LinkedIn::class)
                ->on($campaign->id, $this->actor->describe())
                ->locationCandidates((string) $campaign->ad_account_id, $query);
        } catch (Throwable $exception) {
            return $this->json([
                'ok' => false,
                'error' => $exception->getMessage(),
                'note' => 'Nothing was sent to LinkedIn.',
            ]);
        }

        $keptUrns = array_column($kept, 'urn');
        $fresh = array_values(array_filter(
            $matches,
            fn (array $place): bool => ! in_array($place['urn'], $keptUrns, true),
        ));

        if ($kept === [] && $fresh === []) {
            return $this->json([
                'ok' => false,
                'error' => 'LinkedIn returned no places for that search.',
                'note' => 'Try a more specific place name. Nothing was sent.',
            ]);
        }

        $options = [];

        foreach ($kept as $place) {
            $options[] = [
                'value' => $place['urn'],
                'label' => $place['name'],
                'hint' => $place['urn'],
                'sends' => $place['urn'],
                'selected' => true,
            ];
        }

        foreach (array_slice($fresh, 0, 25) as $place) {
            $options[] = [
                'value' => $place['urn'],
                'label' => $place['name'],
                'hint' => $place['urn'],
                'sends' => $place['urn'],
            ];
        }

        $this->choices->offer(
            'linkedin_locations',
            'Which LinkedIn places should this ad set use?',
            $options,
            multiple: true,
        );

        return $this->json([
            'ok' => true,
            'matches' => count($fresh),
            'kept' => count($kept),
            'note' => 'These are LinkedIn\'s places. Places already chosen stay selected. The Search button on this list searches LinkedIn again and keeps those places. More than one can be selected. Nothing has been sent until the user continues.',
        ]);
    }

    private function offerAudience(): void
    {
        $options = [];

        foreach (LinkedInTargetingFacets::keys() as $facet) {
            $options[] = [
                'value' => $facet,
                'label' => LinkedInTargetingFacets::label($facet),
                'hint' => LinkedInTargetingFacets::searchable($facet) ? 'Search LinkedIn, then pick more than one.' : 'Pick from LinkedIn\'s list.',
                'sends' => 'Change the LinkedIn '.LinkedInTargetingFacets::label($facet).'. Call edit_linkedin_campaign with audience_facet '.$facet.'.'
                    .(LinkedInTargetingFacets::searchable($facet) ? ' Ask what to search for if I have not named it, then pass audience_query.' : ''),
            ];
        }

        $options[] = [
            'value' => 'exclude',
            'label' => 'Exclude people',
            'hint' => 'Any LinkedIn attribute that can be excluded. Age, gender, and member groups cannot.',
            'sends' => 'Exclude people from the LinkedIn audience. Call edit_linkedin_campaign with audience_exclude true and ask which attribute to exclude.',
        ];
        $options[] = [
            'value' => 'matched',
            'label' => 'Matched audiences',
            'hint' => 'List upload, lookalike, predictive, retargeting, or third party.',
            'sends' => 'Include LinkedIn matched audiences. Call edit_linkedin_campaign with matched_audiences as an empty list and matched_operation include.',
        ];
        $options[] = [
            'value' => 'matched_exclude',
            'label' => 'Exclude a matched audience',
            'sends' => 'Exclude LinkedIn matched audiences. Call edit_linkedin_campaign with matched_audiences as an empty list and matched_operation exclude.',
        ];
        $options[] = [
            'value' => 'expansion_on',
            'label' => 'Turn on Audience Expansion',
            'sends' => 'Turn on LinkedIn Audience Expansion. Call edit_linkedin_campaign with audience_expansion true.',
        ];
        $options[] = [
            'value' => 'expansion_off',
            'label' => 'Turn off Audience Expansion',
            'sends' => 'Turn off LinkedIn Audience Expansion. Call edit_linkedin_campaign with audience_expansion false.',
        ];

        $this->choices->offer('linkedin_audience_menu', 'What should change in this LinkedIn audience?', $options);
    }

    private function searchAudience(Campaign $campaign, string $facet, ?string $query, bool $exclude): string
    {
        if ($facet === '' && $exclude) {
            $this->choices->offer(
                'linkedin_audience_exclude',
                'Who should this LinkedIn ad set not reach?',
                array_map(fn (string $key): array => [
                    'value' => $key,
                    'label' => LinkedInTargetingFacets::label($key),
                    'sends' => 'Exclude LinkedIn '.LinkedInTargetingFacets::label($key).'. Call edit_linkedin_campaign with audience_exclude true and audience_facet '.$key.'.'
                        .(LinkedInTargetingFacets::searchable($key) ? ' Ask what to search for, then pass audience_query.' : ''),
                ], LinkedInTargetingFacets::excludableKeys()),
            );

            return $this->json(['ok' => true, 'note' => 'Pick what to exclude. Nothing has been sent.']);
        }

        if (! LinkedInTargetingFacets::exists($facet)) {
            return $this->json(['ok' => false, 'error' => 'Choose an audience attribute from the LinkedIn list.', 'note' => 'Nothing was sent to LinkedIn.']);
        }

        if ($exclude && ! LinkedInTargetingFacets::excludable($facet)) {
            return $this->json(['ok' => false, 'error' => 'LinkedIn does not allow excluding by '.LinkedInTargetingFacets::label($facet).'.', 'note' => 'Nothing was sent to LinkedIn.']);
        }

        if (LinkedInTargetingFacets::searchable($facet) && mb_strlen(trim((string) $query)) < 2) {
            return $this->json([
                'ok' => true,
                'note' => 'Ask which '.mb_strtolower(LinkedInTargetingFacets::label($facet)).' to search for, then call edit_linkedin_campaign with audience_facet '.$facet.' and audience_query. Nothing has been sent.',
            ]);
        }

        try {
            $rows = app(LinkedIn::class)
                ->on($campaign->id, $this->actor->describe())
                ->professionalTargets((string) $campaign->ad_account_id, $facet, $query);
        } catch (Throwable $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage(), 'note' => 'Nothing was sent to LinkedIn.']);
        }

        if ($rows === []) {
            return $this->json(['ok' => false, 'error' => 'LinkedIn returned no '.LinkedInTargetingFacets::label($facet).' matches.', 'note' => 'Try another search. Nothing was sent.']);
        }

        $shown = array_slice($rows, 0, 25);
        $this->choices->offer(
            $exclude ? 'linkedin_audience_exclude' : 'linkedin_audience',
            ($exclude ? 'Exclude' : 'Include').' which LinkedIn '.LinkedInTargetingFacets::label($facet).'?',
            array_map(fn (array $row): array => [
                'value' => (string) $row['urn'],
                'label' => (string) $row['name'],
                'hint' => (string) $row['urn'],
                'sends' => (string) $row['urn'],
            ], $shown),
            multiple: true,
        );

        return $this->json([
            'ok' => true,
            'facet' => $facet,
            'note' => 'More than one can be selected. This adds to the current audience and keeps locations. Nothing has been sent.',
        ]);
    }

    private function offerMatchedAudiences(Campaign $campaign, string $operation): string
    {
        $operation = $operation === 'exclude' ? 'exclude' : 'include';

        try {
            $rows = $this->readySegments($campaign);
        } catch (Throwable $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage(), 'note' => 'Nothing was sent to LinkedIn.']);
        }

        if ($rows === []) {
            return $this->json(['ok' => false, 'error' => 'This LinkedIn account has no ready matched audiences.', 'note' => 'Nothing was sent.']);
        }

        $shown = array_slice($rows, 0, 25);
        $this->choices->offer(
            $operation === 'exclude' ? 'linkedin_matched_exclude' : 'linkedin_matched',
            ($operation === 'exclude' ? 'Exclude' : 'Include').' which LinkedIn matched audiences?',
            array_map(fn (array $row): array => [
                'value' => $row['urn'],
                'label' => $row['name'],
                'hint' => $row['type'].' · '.$row['urn'],
                'sends' => $row['urn'],
            ], $shown),
            multiple: true,
        );

        return $this->json(['ok' => true, 'note' => 'More than one can be selected. Nothing has been sent.']);
    }

    /**
     * @return list<array{urn: string, name: string, type: string}>
     */
    private function readySegments(Campaign $campaign): array
    {
        $account = LinkedInUrn::account((string) $campaign->ad_account_id);
        $rows = [];

        foreach (app(LinkedIn::class)->on($campaign->id, $this->actor->describe())->adSegments((string) $campaign->ad_account_id) as $segment) {
            $id = (string) ($segment['id'] ?? '');
            $name = trim((string) ($segment['name'] ?? ''));

            if (! preg_match('/^[0-9]+$/D', $id) || $name === '' || ($segment['status'] ?? null) !== 'READY' || ($segment['account'] ?? null) !== $account) {
                continue;
            }

            $rows[] = ['urn' => 'urn:li:adSegment:'.$id, 'name' => $name, 'type' => (string) ($segment['type'] ?? 'MATCHED')];
        }

        return $rows;
    }

    /**
     * @param  list<mixed>  $urns
     * @return array<string, mixed>|string
     */
    private function confirmedAttributes(Campaign $campaign, string $facet, array $urns, bool $exclude): array|string
    {
        if (! LinkedInTargetingFacets::exists($facet)) {
            return 'Choose a LinkedIn audience attribute before saving the selection.';
        }

        if ($exclude && ! LinkedInTargetingFacets::excludable($facet)) {
            return 'LinkedIn does not allow excluding by '.LinkedInTargetingFacets::label($facet).'.';
        }

        $chosen = [];

        foreach ($urns as $urn) {
            if (! is_string($urn) || ! LinkedInTargetingFacets::accepts($facet, $urn)) {
                return 'Each choice has to be a LinkedIn '.LinkedInTargetingFacets::label($facet).' id from the search.';
            }

            $chosen[$urn] = $urn;
        }

        $chosen = array_values($chosen);

        $limit = $facet === 'yearsOfExperienceRanges' ? 2 : 100;

        if ($chosen === [] || count($chosen) > $limit) {
            return $facet === 'yearsOfExperienceRanges'
                ? 'Pick one or two LinkedIn years of experience. Two values set the lower and upper limit.'
                : 'Pick between 1 and 100 LinkedIn '.LinkedInTargetingFacets::label($facet).'.';
        }

        try {
            $rows = app(LinkedIn::class)->on($campaign->id, $this->actor->describe())->targetingEntities((string) $campaign->ad_account_id, $chosen);
            $live = app(LinkedIn::class)->on($campaign->id, $this->actor->describe())->campaign((string) $campaign->ad_account_id, (string) $campaign->external_campaign_id);
        } catch (Throwable $exception) {
            return $exception->getMessage();
        }

        $facetUrn = 'urn:li:adTargetingFacet:'.$facet;
        $found = [];

        foreach ($rows as $row) {
            if ((string) ($row['urn'] ?? '') !== '' && ($row['facetUrn'] ?? null) === $facetUrn && in_array($row['urn'], $chosen, true)) {
                $found[] = (string) $row['urn'];
            }
        }

        if (array_diff($chosen, $found) !== []) {
            return 'LinkedIn did not recognise these audience values. Search again and pick from the matches.';
        }

        $audience = (array) ($campaign->audience ?? []);
        $bucket = $exclude ? 'linkedin_exclusions' : 'linkedin_facets';
        $current = (array) ($audience[$bucket][$facet] ?? []);
        $audience[$bucket][$facet] = array_values(array_unique([...$current, ...$chosen]));
        $problems = $this->rules->professionalTargetingProblems($audience);
        $liveFacets = $this->includedFacetKeys(is_array($live['targetingCriteria'] ?? null) ? $live['targetingCriteria'] : []);

        if (! $exclude) {
            $liveFacets[$facet] = $audience['linkedin_facets'][$facet];
            $problems = [...$problems, ...$this->rules->combinationProblems(['linkedin_facets' => $liveFacets])];
        }

        if ($problems !== []) {
            return implode(' ', array_unique($problems));
        }

        return $audience;
    }

    /**
     * @param  list<mixed>  $urns
     * @return list<array{urn: string, name: string, type: string, operation: string}>|string
     */
    private function confirmedMatched(Campaign $campaign, array $urns, string $operation): array|string
    {
        $operation = $operation === 'exclude' ? 'exclude' : 'include';
        $chosen = [];

        foreach ($urns as $urn) {
            if (! is_string($urn) || ! preg_match('/^urn:li:adSegment:[0-9]+$/D', $urn)) {
                return 'Each matched audience has to be a urn:li:adSegment id from the list.';
            }

            $chosen[$urn] = $urn;
        }

        try {
            $ready = $this->readySegments($campaign);
        } catch (Throwable $exception) {
            return $exception->getMessage();
        }

        $byUrn = [];

        foreach ($ready as $row) {
            $byUrn[$row['urn']] = $row;
        }

        $saved = [];

        foreach ($chosen as $urn) {
            if (! isset($byUrn[$urn])) {
                return 'LinkedIn did not recognise '.$urn.' as a ready matched audience. Choose from the list.';
            }

            $saved[] = [...$byUrn[$urn], 'operation' => $operation];
        }

        return $saved;
    }

    /**
     * @param  array<string, mixed>  $audience
     * @param  list<array{urn: string, name: string, type: string, operation: string}>  $matched
     * @return array<string, mixed>
     */
    private function withMatched(array $audience, array $matched): array
    {
        $current = array_values(array_filter((array) ($audience['linkedin_matched'] ?? []), fn (mixed $row): bool => is_array($row)));

        foreach ($matched as $segment) {
            $current = array_values(array_filter($current, fn (array $row): bool => ($row['urn'] ?? null) !== $segment['urn']));
            $current[] = $segment;
        }

        $audience['linkedin_matched'] = $current;

        return $audience;
    }

    /**
     * @param  array<string, mixed>  $criteria
     * @return array<string, list<string>>
     */
    private function includedFacetKeys(array $criteria): array
    {
        $facets = [];

        foreach ((array) ($criteria['include']['and'] ?? []) as $clause) {
            if (! is_array($clause)) {
                continue;
            }

            foreach ((array) ($clause['or'] ?? []) as $facet => $urns) {
                if (! is_string($facet) || ! str_starts_with($facet, 'urn:li:adTargetingFacet:') || ! is_array($urns)) {
                    continue;
                }

                $key = substr($facet, strlen('urn:li:adTargetingFacet:'));

                if (LinkedInTargetingFacets::exists($key)) {
                    $facets[$key] = array_values(array_filter($urns, 'is_string'));
                }
            }
        }

        return $facets;
    }

    /**
     * @param  list<mixed>  $urns
     * @return list<array{urn: string, name: string}>|string
     */
    private function confirmedPlaces(Campaign $campaign, array $urns): array|string
    {
        $chosen = [];

        foreach ($urns as $urn) {
            if (! is_string($urn) || ! preg_match('/^urn:li:geo:[0-9]+$/D', $urn)) {
                return 'Each LinkedIn location has to be a urn:li:geo id from the search.';
            }

            $chosen[$urn] = $urn;
        }

        $chosen = array_values($chosen);

        if ($chosen === [] || count($chosen) > 50) {
            return 'Pick between 1 and 50 LinkedIn places.';
        }

        try {
            $rows = app(LinkedIn::class)
                ->on($campaign->id, $this->actor->describe())
                ->targetingEntities((string) $campaign->ad_account_id, $chosen);
        } catch (Throwable $exception) {
            return $exception->getMessage();
        }

        $names = [];

        foreach ($rows as $row) {
            $urn = (string) ($row['urn'] ?? '');
            $name = trim((string) ($row['name'] ?? ''));

            if ($name === '' || ! in_array($urn, $chosen, true)) {
                continue;
            }

            if (($row['facetUrn'] ?? null) !== 'urn:li:adTargetingFacet:locations') {
                continue;
            }

            $names[$urn] = $name;
        }

        $missing = array_values(array_diff($chosen, array_keys($names)));

        if ($missing !== []) {
            return 'LinkedIn did not recognise these places: '.implode(', ', $missing).'. Search again and pick from the matches.';
        }

        return array_map(
            fn (string $urn): array => ['urn' => $urn, 'name' => $names[$urn]],
            $chosen,
        );
    }

    /**
     * @param  array<string, mixed>  $given
     */
    private function refusal(Campaign $campaign, array $given): ?string
    {
        if (array_key_exists('name', $given)) {
            $local = $this->localName((string) $given['name']);
            $sent = 'ARB-'.$local;

            if ($local === '' || strlen($sent) > 200) {
                return 'The ad set name has to be between 1 and 200 bytes.';
            }
        }

        if (array_key_exists('budget', $given)) {
            $amount = $given['budget'];
            $ceiling = BudgetCeiling::for($campaign);

            if (! is_numeric($amount) || (float) $amount <= 0) {
                return 'The budget has to be a number above zero.';
            }

            if ($ceiling === null) {
                return BudgetCeiling::missingReason($campaign);
            }

            if ((float) $amount > $ceiling) {
                return sprintf('The budget cannot be above %s %s.', $campaign->currency ?: 'USD', $ceiling);
            }
        }

        if (array_key_exists('bid_strategy', $given) && ! in_array($given['bid_strategy'], $this->rules->bidStrategies($campaign->objective), true)) {
            return 'LinkedIn bidding here is automated, target cost, or maximum bid. This objective may not offer target cost.';
        }

        $strategy = (string) ($given['bid_strategy'] ?? $campaign->bid_strategy ?: 'AUTOMATED_BID');

        if ($strategy === 'AUTOMATED_BID' && array_key_exists('bid_amount', $given)) {
            return 'Automated bidding does not take a target cost. Choose target cost or maximum bid first.';
        }

        if (in_array($strategy, ['TARGET_COST', 'MAXIMUM_BID'], true)) {
            $amount = $given['bid_amount'] ?? $campaign->bid_amount;

            if (! is_numeric($amount) || (float) $amount <= 0) {
                return 'Target cost and maximum bid need a number above zero.';
            }
        }

        if (! empty($given['continuous']) && array_key_exists('ends_at', $given)) {
            return 'Pass an end date, or continuous, not both.';
        }

        if (array_key_exists('ends_at', $given) || ! empty($given['continuous'])) {
            if ($campaign->starts_at === null) {
                return 'The start on a running LinkedIn campaign cannot move, and this campaign has no start recorded, so the end date was not sent.';
            }
        }

        if (array_key_exists('ends_at', $given)) {
            try {
                $end = Carbon::parse((string) $given['ends_at']);
            } catch (Throwable) {
                return 'The end date could not be read.';
            }

            if ($end->lessThanOrEqualTo($campaign->starts_at)) {
                return 'The end date has to be after the start. The start cannot move.';
            }
        }

        if (array_key_exists('placements', $given)) {
            $chosen = $this->chosenPlacements($given['placements']);

            if (! is_array($given['placements']) || $chosen === [] || count($chosen) !== count(array_unique($given['placements']))) {
                return 'LinkedIn placements are linkedin_feed and linkedin_audience_network. Both can be selected.';
            }
        }

        if (array_key_exists('locations', $given)) {
            if (! is_array($given['locations'])) {
                return 'Each LinkedIn location has to be a urn:li:geo id from the search.';
            }

            foreach ($given['locations'] as $urn) {
                if (! is_string($urn) || ! preg_match('/^urn:li:geo:[0-9]+$/D', $urn)) {
                    return 'Each LinkedIn location has to be a urn:li:geo id from the search.';
                }
            }
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $given
     * @param  list<array{urn: string, name: string}>|null  $places
     * @return array<string, mixed>
     */
    private function stored(array $given, ?array $places = null): array
    {
        $stored = [];

        if (array_key_exists('name', $given)) {
            $stored['name'] = $this->localName((string) $given['name']);
        }

        if (array_key_exists('budget', $given)) {
            $stored['budget'] = round((float) $given['budget'], 2);
        }

        if (array_key_exists('bid_strategy', $given)) {
            $stored['bid_strategy'] = (string) $given['bid_strategy'];

            if ($stored['bid_strategy'] === 'AUTOMATED_BID') {
                $stored['bid_amount'] = null;
            }
        }

        if (array_key_exists('bid_amount', $given)) {
            $stored['bid_amount'] = round((float) $given['bid_amount'], 2);
        }

        if (! empty($given['continuous'])) {
            $stored['ends_at'] = null;
        }

        if (array_key_exists('ends_at', $given)) {
            $stored['ends_at'] = Carbon::parse((string) $given['ends_at']);
        }

        if (array_key_exists('placements', $given)) {
            $stored['placements'] = $this->chosenPlacements($given['placements']);
        }

        if ($places !== null) {
            $stored['locations'] = [
                ...(array) ($this->focused()?->locations ?? []),
                'linkedin_places' => $places,
            ];
        }

        return $stored;
    }

    /**
     * @return list<string>
     */
    private function chosenPlacements(mixed $value): array
    {
        if (! is_array($value)) {
            return [];
        }

        $picked = [];

        foreach ($value as $item) {
            if (is_string($item) && in_array($item, $this->rules->placements(), true)) {
                $picked[$item] = true;
            }
        }

        return array_values(array_filter(
            $this->rules->placements(),
            static fn (string $placement): bool => isset($picked[$placement]),
        ));
    }

    private function localName(string $name): string
    {
        $name = trim($name);

        if (str_starts_with($name, 'ARB-')) {
            $name = trim(substr($name, 4));
        }

        return $name;
    }

    /** @return array<string, mixed> */
    private function present(Request $request): array
    {
        return array_filter(
            $request->all(),
            static fn (mixed $value): bool => $value !== null && $value !== '',
        );
    }

    /** @return array<string, mixed> */
    private function given(Request $request): array
    {
        return array_intersect_key($this->present($request), array_flip(self::FIELDS));
    }
}
