<?php

namespace App\Agent\Tools\Campaign;

use App\Agent\Choices;
use App\Agent\Tools\Campaign\Concerns\ActsOnFocusedCampaign;
use App\Agent\Workspace;
use App\Campaigns\Platforms\LinkedInRules;
use App\Campaigns\Targeting\LinkedInAudienceSize;
use App\Models\ArtifactFieldSource;
use App\Models\Campaign;
use App\Services\LinkedIn\LinkedInRestApi;
use App\Services\LinkedIn\LinkedInTargetingFacets;
use App\Services\Platforms\Support\CallLogger;
use App\Support\Actor;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Stringable;
use Throwable;

class ChooseLinkedInResource implements Tool
{
    use ActsOnFocusedCampaign;

    public function __construct(
        private readonly Workspace $workspace,
        private readonly Choices $choices,
        private readonly LinkedInRestApi $api,
        private readonly Actor $actor,
    ) {}

    public function description(): Stringable|string
    {
        return 'Choose a published Lead Gen Form or enabled conversion rule for the focused draft, or refine its professional audience. Omit the ID to show choices for section. Every publish creates its own new campaign group, so there is no group to choose. Never invent resource IDs.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'section' => $schema->string()->enum(['lead_form', 'conversion', 'audience', 'insight_tag'])->description('Resource to list. Insight Tag verification checks account and landing domain.'),
            'review_audience' => $schema->boolean()->description('When reviewing or changing the professional audience, set true to show audience modes first without changing saved targeting.'),
            'audience_mode' => $schema->string()->enum(self::audienceModes())->description('LinkedIn audience refinement. Facet modes add included filters to the saved audience without clearing other filters; exclude lists the facets people can be excluded by; broad clears every filter and exclusion; remove lists saved filters and exclusions to remove; done keeps the audience; confirm_small_audience accepts an audience LinkedIn estimates below 300 members.'),
            'exclude_facet' => $schema->string()->enum(LinkedInTargetingFacets::excludableKeys())->description('Exclude people by this facet. Pass with query to search a searchable attribute. Age, gender, and member groups cannot be excluded.'),
            'query' => $schema->string()->description('Search text for titles, industries or employers, 2 to 100 characters. Seniorities, company size, age and gender are fixed lists and need no query.'),
            'selection' => $schema->array()->items($schema->string())->description('Exact facet|URN values selected from the current professional targeting options. They are added to that facet.'),
            'exclude_selection' => $schema->array()->items($schema->string())->description('Exact facet|URN values selected from the current exclusion options. They are added to that facet\'s exclusions.'),
            'remove' => $schema->array()->items($schema->string())->description('Saved facet|URN filters, or exclude:facet|URN exclusions, to remove from the audience.'),
            'conflict' => $schema->string()->enum(['replace', 'keep'])->description('Answer to an incompatible selection: replace the conflicting filter, or keep the current audience.'),
            'lead_form_id' => $schema->string()->description('Published form ID selected from current results.'),
            'conversion_id' => $schema->string()->description('Enabled account-owned conversion ID selected from current results.'),
        ];
    }

    public function handle(Request $request): Stringable|string
    {
        if (! $campaign = $this->focused()) {
            return $this->noCampaign();
        }
        if ($campaign->platform !== 'linkedin' || $campaign->isPublished() || blank($campaign->ad_account_id)) {
            return $this->json(['ok' => false, 'error' => 'Choose a verified account on a draft LinkedIn campaign first.']);
        }
        app(CallLogger::class)->attributeTo($campaign->id, $this->actor->describe());
        $arguments = $request->all();
        if (($arguments['section'] ?? null) === 'insight_tag') {
            try {
                $health = $this->api->insightTagHealth((string) $campaign->ad_account_id, (string) $campaign->landing_url);
                $setup = (array) ($campaign->meta['linkedin_setup'] ?? []);
                $setup['insight_tag'] = $health;
                $campaign->update(['meta' => [...(array) $campaign->meta, 'linkedin_setup' => $setup]]);

                return $this->json(['ok' => true, 'insight_tag' => $health]);
            } catch (Throwable $exception) {
                return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
            }
        }
        if (($arguments['section'] ?? null) === 'audience' || isset($arguments['audience_mode']) || isset($arguments['selection'])
            || isset($arguments['remove']) || isset($arguments['conflict'])
            || isset($arguments['exclude_facet']) || isset($arguments['exclude_selection'])
            || (isset($arguments['query']) && isset($campaign->meta['linkedin_audience_mode']))) {
            return $this->audience($campaign, $arguments);
        }
        $section = array_key_exists('lead_form_id', $arguments) ? 'lead_form'
            : (array_key_exists('conversion_id', $arguments) ? 'conversion' : ($arguments['section'] ?? null));
        $field = match ($section) {
            'lead_form' => 'lead_form_id', 'conversion' => 'conversion_id', default => null,
        };
        if ($field === null) {
            return $this->json(['ok' => false, 'error' => 'Choose lead_form, conversion, audience, or insight_tag. Every publish creates its own new campaign group, so there is none to choose.']);
        }
        if (($section === 'lead_form' && $campaign->objective !== 'LEAD_GENERATION')
            || ($section === 'conversion' && $campaign->objective !== 'WEBSITE_CONVERSIONS')) {
            return $this->json(['ok' => false, 'error' => 'This resource does not match the selected objective.']);
        }
        try {
            $rows = match ($section) {
                'lead_form' => $this->api->leadForms((string) $campaign->ad_account_id),
                'conversion' => $this->api->conversions((string) $campaign->ad_account_id),
            };
            $selected = isset($arguments[$field]) ? collect($rows)->first(fn (array $row): bool => (string) $row['id'] === (string) $arguments[$field]) : null;
            if (isset($arguments[$field])) {
                if ($selected === null) {
                    return $this->json(['ok' => false, 'error' => 'This resource is unavailable or outside the selected account. Refresh the choices.']);
                }
                $setup = (array) ($campaign->meta['linkedin_setup'] ?? []);
                $setup[$section] = $selected;
                $campaign->update(['meta' => [...(array) $campaign->meta, 'linkedin_setup' => $setup]]);
                $this->workspace->recordSource($campaign, $field, ArtifactFieldSource::PLATFORM_RETURNED);

                return $this->json(['ok' => true, 'selected' => $selected]);
            }
            if ($rows === []) {
                return $this->json(['ok' => false, 'error' => 'No eligible '.str_replace('_', ' ', $section).' is available for this account. Configure it in LinkedIn Campaign Manager first.']);
            }
            $this->choices->offer('linkedin_'.$field, 'Choose the LinkedIn '.str_replace('_', ' ', $section).'.', array_map(fn (array $row): array => [
                'value' => (string) $row['id'], 'label' => $row['name'] ?? (string) $row['id'],
                'sends' => 'Use LinkedIn '.str_replace('_', ' ', $section).' '.$row['id'],
            ], $rows));

            return $this->json(['ok' => true, 'resources' => $rows]);
        } catch (Throwable $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }
    }

    private function audience(Campaign $campaign, array $arguments): string
    {
        if (isset($arguments['conflict'])) {
            return $this->resolveConflict($campaign, (string) $arguments['conflict']);
        }
        if (isset($arguments['remove'])) {
            return $this->removeFilters($campaign, (array) $arguments['remove']);
        }
        $exclude = isset($arguments['exclude_facet']) || isset($arguments['exclude_selection'])
            || (! isset($arguments['audience_mode']) && ! isset($arguments['selection'])
                && ($campaign->meta['linkedin_audience_operation'] ?? null) === 'exclude');
        $mode = $arguments['exclude_facet'] ?? $arguments['audience_mode'] ?? $campaign->meta['linkedin_audience_mode'] ?? null;
        if ($mode === null || ($arguments['review_audience'] ?? false)) {
            return $this->offerAudienceMenu($campaign);
        }
        if (! in_array($mode, self::audienceModes(), true)) {
            return $this->json(['ok' => false, 'error' => 'Choose a supported LinkedIn audience refinement.']);
        }
        if ($mode === 'done') {
            return $this->keepAudience($campaign);
        }
        if ($mode === 'confirm_small_audience') {
            if (! app(LinkedInAudienceSize::class)->confirm($campaign)) {
                return $this->json(['ok' => false, 'error' => 'There is no current small-audience estimate to confirm. Review the audience again.']);
            }
            $campaign->update(['meta' => [...(array) $campaign->meta, 'linkedin_audience_reviewed' => true]]);

            return $this->json(['ok' => true, 'note' => 'The buyer accepted publishing with an audience below LinkedIn\'s 300-member minimum. LinkedIn may not deliver it.']);
        }
        if ($mode === 'remove') {
            return $this->offerRemoval($campaign);
        }
        if ($mode === 'exclude') {
            return $this->offerExclusionFacets($campaign);
        }
        if ($exclude && ! LinkedInTargetingFacets::excludable($mode)) {
            $this->offerExclusionFacets($campaign);

            return $this->json(['ok' => false, 'error' => 'LinkedIn does not allow excluding people by '.LinkedInTargetingFacets::label($mode).'.']);
        }
        $campaign->update(['meta' => [...(array) $campaign->meta, 'linkedin_audience_mode' => $mode,
            'linkedin_audience_operation' => $exclude ? 'exclude' : 'include',
            ...isset($arguments['audience_mode']) || isset($arguments['exclude_facet']) ? ['linkedin_audience_reviewed' => false] : []]]);
        if ($mode === 'broad') {
            $set = $campaign->targetingSet;
            if ($set !== null && isset($set->options['linkedin_segments'])) {
                $options = (array) $set->options;
                unset($options['linkedin_segments']);
                $set->update(['options' => $options, 'revision' => $set->revision + 1]);
            }
            $campaign->update(['audience' => array_diff_key((array) $campaign->audience, ['linkedin_facets' => true, 'linkedin_exclusions' => true]),
                'meta' => [...array_diff_key((array) $campaign->meta, ['linkedin_audience_labels' => true, 'linkedin_audience_pending' => true]),
                    'linkedin_audience_reviewed' => true]]);

            return $this->json(['ok' => true, 'note' => 'Broad professional audience selected within the chosen locations. All professional filters and exclusions were cleared.']);
        }
        if ($mode === 'retargeting') {
            return (string) app(ChooseAudienceList::class)->handle(new Request([]));
        }
        $searchable = LinkedInTargetingFacets::searchable($mode);
        $search = $searchable ? ($arguments['query'] ?? $campaign->meta['linkedin_audience_query'][$mode] ?? null) : null;
        if ($searchable && blank($search)) {
            $this->offerAudienceSearch($mode, exclude: $exclude);

            return $this->json(['ok' => true, 'note' => 'Ask which '.mb_strtolower(LinkedInTargetingFacets::label($mode)).' to search for. Do not invent URNs.']);
        }
        if ($searchable && isset($arguments['query'])) {
            $queries = (array) ($campaign->meta['linkedin_audience_query'] ?? []);
            $queries[$mode] = $search;
            $campaign->update(['meta' => [...(array) $campaign->meta,
                'linkedin_audience_query' => $queries, 'linkedin_audience_reviewed' => false]]);
        }
        try {
            $rows = $this->api->professionalTargets((string) $campaign->ad_account_id, $mode, $search);
            if ($exclude && isset($arguments['exclude_selection'])) {
                return $this->addExclusion($campaign, $mode, $search, (array) $arguments['exclude_selection'], $rows);
            }
            if (! $exclude && isset($arguments['selection'])) {
                return $this->addSelection($campaign, $mode, $search, (array) $arguments['selection'], $rows);
            }
            if ($rows === [] && ! $searchable) {
                $this->offerAudienceMenu($campaign);

                return $this->json(['ok' => false, 'error' => 'LinkedIn returned no '.LinkedInTargetingFacets::label($mode).' options for this account.']);
            }
            if ($rows === []) {
                $this->offerAudienceSearch($mode, 'No verified LinkedIn matches were found. Try a different search.', $exclude);

                return $this->json(['ok' => false, 'error' => 'No verified targeting matches. Try a different search.']);
            }
            if ($searchable) {
                $queries = (array) ($campaign->meta['linkedin_audience_query'] ?? []);
                $queries[$mode] = $search;
                $campaign->update(['meta' => [...(array) $campaign->meta, 'linkedin_audience_query' => $queries]]);
            }
            if ($exclude) {
                return $this->offerExclusionResults($campaign, $mode, $rows);
            }
            $saved = (array) ($campaign->audience['linkedin_facets'][$mode] ?? []);
            $policy = LinkedInTargetingFacets::hasPolicyRestriction($mode) ? ' '.LinkedInTargetingFacets::POLICY_WARNING : '';
            $this->choices->offer('linkedin_professional_selection', 'Choose LinkedIn '.LinkedInTargetingFacets::label($mode).' to add.'.$policy, array_map(fn (array $row): array => [
                'value' => $mode.'|'.$row['urn'], 'label' => $row['name'], 'sends' => 'Target '.$row['name'],
                ...in_array($row['urn'], $saved, true) ? ['hint' => 'Already in this audience']
                    : (in_array($row['urn'], (array) ($campaign->audience['linkedin_exclusions'][$mode] ?? []), true) ? ['hint' => 'Excluded from this audience'] : []),
            ], $rows), multiple: true, allowOther: $searchable,
                otherLabel: 'Enter it myself',
                otherHint: 'Search for a different professional audience.',
                otherPlaceholder: LinkedInTargetingFacets::placeholder($mode) ?: null);

            return $this->json(['ok' => true, 'results' => $rows, ...$policy === '' ? [] : ['warning' => LinkedInTargetingFacets::POLICY_WARNING]]);
        } catch (Throwable $exception) {
            $searchable
                ? $this->offerAudienceSearch($mode, 'LinkedIn search is unavailable. Try another search when access is restored.', $exclude)
                : $this->offerAudienceMenu($campaign);

            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }
    }

    /** @return list<string> */
    private static function audienceModes(): array
    {
        return ['broad', 'retargeting', ...LinkedInTargetingFacets::keys(), 'exclude', 'remove', 'done', 'confirm_small_audience'];
    }

    /**
     * Add the selected values to the facet, keeping every other filter.
     *
     * @param  list<string>  $selection
     * @param  list<array<string, mixed>>  $rows
     */
    private function addSelection(Campaign $campaign, string $mode, ?string $search, array $selection, array $rows): string
    {
        $selected = array_values(array_unique($selection));
        $names = collect($rows)->mapWithKeys(fn (array $row): array => [$mode.'|'.$row['urn'] => (string) $row['name']])->all();
        if ($selected === [] || array_diff($selected, array_keys($names)) !== []) {
            return $this->json(['ok' => false, 'error' => 'Select current verified targeting results; no audience was saved.']);
        }
        $urns = array_map(fn (string $value): string => explode('|', $value, 2)[1], $selected);
        $labels = [];
        foreach ($selected as $value) {
            $labels[explode('|', $value, 2)[1]] = $names[$value];
        }
        $facets = (array) ($campaign->audience['linkedin_facets'] ?? []);
        $merged = array_values(array_unique([...(array) ($facets[$mode] ?? []), ...$urns]));
        if (count($merged) > 100) {
            return $this->json(['ok' => false, 'error' => 'LinkedIn allows up to 100 '.mb_strtolower(LinkedInTargetingFacets::label($mode)).' in one audience; no audience was saved.']);
        }
        $proposed = [...(array) $campaign->audience, 'linkedin_facets' => [...$facets, $mode => $merged]];
        if ($clashes = app(LinkedInRules::class)->exclusionProblems($proposed)) {
            $this->offerAudienceMenu($campaign);

            return $this->json(['ok' => false, 'error' => implode(' ', $clashes).' No audience was saved.']);
        }
        $problems = app(LinkedInRules::class)->combinationProblems($proposed);
        if ($problems !== []) {
            $campaign->update(['meta' => [...(array) $campaign->meta, 'linkedin_audience_pending' => [
                'facet' => $mode, 'urns' => $urns, 'labels' => $labels, 'query' => $search,
            ]]]);
            $this->offerConflict($campaign, $mode);

            return $this->json(['ok' => false, 'error' => implode(' ', $problems), 'note' => 'Ask whether to replace the conflicting filter or keep the current audience.']);
        }

        return $this->saveFacets($campaign, [...$facets, $mode => $merged], $labels, [$mode => $search],
            LinkedInTargetingFacets::hasPolicyRestriction($mode));
    }

    /**
     * Add the selected values to the facet's exclusions, keeping every other filter.
     *
     * @param  list<string>  $selection
     * @param  list<array<string, mixed>>  $rows
     */
    private function addExclusion(Campaign $campaign, string $mode, ?string $search, array $selection, array $rows): string
    {
        $selected = array_values(array_unique($selection));
        $names = collect($rows)->mapWithKeys(fn (array $row): array => [$mode.'|'.$row['urn'] => (string) $row['name']])->all();
        if ($selected === [] || array_diff($selected, array_keys($names)) !== []) {
            return $this->json(['ok' => false, 'error' => 'Select current verified targeting results to exclude; no audience was saved.']);
        }
        $labels = [];
        foreach ($selected as $value) {
            $labels[explode('|', $value, 2)[1]] = $names[$value];
        }
        $exclusions = (array) ($campaign->audience['linkedin_exclusions'] ?? []);
        $merged = array_values(array_unique([...(array) ($exclusions[$mode] ?? []), ...array_keys($labels)]));
        if (count($merged) > 100) {
            return $this->json(['ok' => false, 'error' => 'LinkedIn allows up to 100 excluded '.mb_strtolower(LinkedInTargetingFacets::label($mode)).'; no audience was saved.']);
        }
        $exclusions[$mode] = $merged;
        if ($problems = app(LinkedInRules::class)->exclusionProblems([...(array) $campaign->audience, 'linkedin_exclusions' => $exclusions])) {
            $this->offerAudienceMenu($campaign);

            return $this->json(['ok' => false, 'error' => implode(' ', $problems).' No audience was saved.']);
        }

        return $this->saveFacets($campaign, (array) ($campaign->audience['linkedin_facets'] ?? []), $labels, [$mode => $search], exclusions: $exclusions);
    }

    private function offerExclusionFacets(Campaign $campaign): string
    {
        $exclusions = (array) ($campaign->audience['linkedin_exclusions'] ?? []);
        $this->choices->offer('linkedin_audience_exclude', 'Who should this LinkedIn campaign not reach? Age and gender can only be included, not excluded.',
            array_map(fn (string $facet): array => [
                'value' => $facet, 'label' => LinkedInTargetingFacets::label($facet),
                ...count((array) ($exclusions[$facet] ?? [])) > 0 ? ['hint' => count((array) $exclusions[$facet]).' excluded, add more'] : [],
                'sends' => 'Exclude people by LinkedIn '.mb_strtolower(LinkedInTargetingFacets::label($facet)),
            ], LinkedInTargetingFacets::excludableKeys()));

        return $this->json(['ok' => true, 'note' => 'Let the buyer choose what to exclude people by.']);
    }

    /** @param  list<array<string, mixed>>  $rows */
    private function offerExclusionResults(Campaign $campaign, string $mode, array $rows): string
    {
        $excluded = (array) ($campaign->audience['linkedin_exclusions'][$mode] ?? []);
        $included = (array) ($campaign->audience['linkedin_facets'][$mode] ?? []);
        $searchable = LinkedInTargetingFacets::searchable($mode);
        $this->choices->offer('linkedin_professional_exclusion', 'Choose LinkedIn '.LinkedInTargetingFacets::label($mode).' to exclude.', array_map(fn (array $row): array => [
            'value' => $mode.'|'.$row['urn'], 'label' => $row['name'], 'sends' => 'Exclude '.$row['name'],
            ...in_array($row['urn'], $excluded, true) ? ['hint' => 'Already excluded']
                : (in_array($row['urn'], $included, true) ? ['hint' => 'Included in this audience'] : []),
        ], $rows), multiple: true, allowOther: $searchable,
            otherLabel: 'Enter it myself',
            otherHint: 'Search for something else to exclude.',
            otherPlaceholder: LinkedInTargetingFacets::placeholder($mode) ?: null);

        return $this->json(['ok' => true, 'results' => $rows, 'note' => 'These will be excluded, not targeted.']);
    }

    /**
     * @param  array<string, list<string>>  $facets
     * @param  array<string, string>  $labels
     * @param  array<string, string|null>  $queries
     */
    private function saveFacets(Campaign $campaign, array $facets, array $labels, array $queries = [], bool $policy = false, array $audience = [], ?array $exclusions = null): string
    {
        $facets = array_filter($facets, fn (array $urns): bool => $urns !== []);
        $exclusions = array_filter($exclusions ?? (array) ($campaign->audience['linkedin_exclusions'] ?? []), fn (mixed $urns): bool => (array) $urns !== []);
        $kept = array_merge([], ...array_values($facets), ...array_values(array_map(fn (mixed $urns): array => (array) $urns, $exclusions)));
        $savedLabels = array_intersect_key([...(array) ($campaign->meta['linkedin_audience_labels'] ?? []), ...$labels], array_flip($kept));
        $savedQueries = [...(array) ($campaign->meta['linkedin_audience_query'] ?? []), ...array_filter($queries, fn (?string $query): bool => filled($query))];
        $campaign->update([
            'audience' => [...array_diff_key($audience ?: (array) $campaign->audience, ['linkedin_facets' => true, 'linkedin_exclusions' => true]),
                ...$facets === [] ? [] : ['linkedin_facets' => $facets], ...$exclusions === [] ? [] : ['linkedin_exclusions' => $exclusions]],
            'meta' => [...array_diff_key((array) $campaign->meta, ['linkedin_audience_pending' => true]),
                'linkedin_audience_reviewed' => true, 'linkedin_audience_labels' => $savedLabels, 'linkedin_audience_query' => $savedQueries],
        ]);
        $size = app(LinkedInAudienceSize::class)->refresh($campaign);
        $this->offerAudienceMenu($campaign, 'Audience updated.');

        return $this->json(['ok' => true, 'selected' => $facets, ...$exclusions === [] ? [] : ['excluded' => $exclusions], 'audience' => $this->audienceSummary($campaign),
            'estimate' => app(LinkedInAudienceSize::class)->describe($size),
            ...$policy ? ['warning' => LinkedInTargetingFacets::POLICY_WARNING] : [],
            'note' => 'Saved. Every other filter was kept. Ask whether to add another filter, remove one, or keep this audience.']);
    }

    private function resolveConflict(Campaign $campaign, string $choice): string
    {
        $pending = $campaign->meta['linkedin_audience_pending'] ?? null;
        if (! is_array($pending) || ! LinkedInTargetingFacets::exists((string) ($pending['facet'] ?? '')) || ! in_array($choice, ['replace', 'keep'], true)) {
            return $this->json(['ok' => false, 'error' => 'There is no conflicting LinkedIn selection waiting. Review the audience again.']);
        }
        if ($choice === 'keep') {
            $campaign->update(['meta' => array_diff_key((array) $campaign->meta, ['linkedin_audience_pending' => true])]);

            return $this->offerAudienceMenu($campaign, 'Kept the current audience.');
        }
        $facet = (string) $pending['facet'];
        $replaced = LinkedInTargetingFacets::incompatibleWith($facet);
        $facets = array_diff_key((array) ($campaign->audience['linkedin_facets'] ?? []), array_flip($replaced));
        $facets[$facet] = array_values(array_unique([...(array) ($facets[$facet] ?? []), ...(array) $pending['urns']]));
        $audience = (array) $campaign->audience;
        if (in_array('seniorities', $replaced, true)) {
            unset($audience['seniorities']);
        }

        return $this->saveFacets($campaign, $facets, (array) ($pending['labels'] ?? []), [$facet => $pending['query'] ?? null],
            LinkedInTargetingFacets::hasPolicyRestriction($facet), $audience);
    }

    /** @param  list<string>  $values */
    private function removeFilters(Campaign $campaign, array $values): string
    {
        $facets = (array) ($campaign->audience['linkedin_facets'] ?? []);
        $exclusions = (array) ($campaign->audience['linkedin_exclusions'] ?? []);
        $current = [...$this->filterValues($facets), ...$this->filterValues($exclusions, 'exclude:')];
        $values = array_values(array_unique($values));
        if ($values === [] || array_diff($values, $current) !== []) {
            return $this->json(['ok' => false, 'error' => 'Choose saved filters to remove; nothing was changed.']);
        }
        foreach ($values as $value) {
            $excluded = str_starts_with($value, 'exclude:');
            [$facet, $urn] = explode('|', $excluded ? substr($value, 8) : $value, 2);
            if ($excluded) {
                $exclusions[$facet] = array_values(array_diff((array) $exclusions[$facet], [$urn]));
            } else {
                $facets[$facet] = array_values(array_diff((array) $facets[$facet], [$urn]));
            }
        }

        return $this->saveFacets($campaign, $facets, [], exclusions: $exclusions);
    }

    /**
     * @param  array<string, mixed>  $facets
     * @return list<string>
     */
    private function filterValues(array $facets, string $prefix = ''): array
    {
        $values = [];
        foreach ($facets as $facet => $urns) {
            foreach ((array) $urns as $urn) {
                $values[] = $prefix.$facet.'|'.$urn;
            }
        }

        return $values;
    }

    private function offerRemoval(Campaign $campaign): string
    {
        $labels = (array) ($campaign->meta['linkedin_audience_labels'] ?? []);
        $options = [];
        foreach ((array) ($campaign->audience['linkedin_facets'] ?? []) as $facet => $urns) {
            foreach ((array) $urns as $urn) {
                $options[] = ['value' => $facet.'|'.$urn, 'label' => LinkedInTargetingFacets::label((string) $facet).': '.($labels[$urn] ?? $urn),
                    'sends' => 'Remove '.($labels[$urn] ?? $urn).' from the LinkedIn audience'];
            }
        }
        foreach ((array) ($campaign->audience['linkedin_exclusions'] ?? []) as $facet => $urns) {
            foreach ((array) $urns as $urn) {
                $options[] = ['value' => 'exclude:'.$facet.'|'.$urn, 'label' => 'Excluded '.LinkedInTargetingFacets::label((string) $facet).': '.($labels[$urn] ?? $urn),
                    'sends' => 'Stop excluding '.($labels[$urn] ?? $urn).' from the LinkedIn audience'];
            }
        }
        if ($options === []) {
            return $this->offerAudienceMenu($campaign, 'There are no professional filters to remove.');
        }
        $this->choices->offer('linkedin_audience_remove', 'Choose the LinkedIn filters or exclusions to remove. Everything else is kept.', $options, multiple: true);

        return $this->json(['ok' => true, 'note' => 'Let the buyer pick the filters to remove.']);
    }

    private function offerConflict(Campaign $campaign, string $facet): void
    {
        $conflicting = array_values(array_filter(LinkedInTargetingFacets::incompatibleWith($facet),
            fn (string $other): bool => ! empty($campaign->audience['linkedin_facets'][$other]) || ($other === 'seniorities' && ! empty($campaign->audience['seniorities']))));
        $names = implode(' and ', array_map(LinkedInTargetingFacets::label(...), $conflicting));
        $this->choices->offer('linkedin_audience_conflict', 'LinkedIn cannot combine '.LinkedInTargetingFacets::label($facet).' with '.$names.'. Which should this audience use?', [
            ['value' => 'replace', 'label' => 'Use '.LinkedInTargetingFacets::label($facet).' instead', 'hint' => 'Removes '.$names.' and keeps every other filter.',
                'sends' => 'Replace '.$names.' with the new '.LinkedInTargetingFacets::label($facet).' selection'],
            ['value' => 'keep', 'label' => 'Keep '.$names, 'hint' => 'Discards the new selection.',
                'sends' => 'Keep the current LinkedIn audience'],
        ]);
    }

    private function keepAudience(Campaign $campaign): string
    {
        $campaign->update(['meta' => [...array_diff_key((array) $campaign->meta, ['linkedin_audience_pending' => true]), 'linkedin_audience_reviewed' => true]]);
        $sizer = app(LinkedInAudienceSize::class);
        $size = $sizer->current($campaign) ?? $sizer->refresh($campaign);
        if ($sizer->needsConfirmation($campaign)) {
            $this->offerAudienceMenu($campaign);

            return $this->json(['ok' => true, 'warning' => 'LinkedIn estimates this audience below 300 members, its minimum to deliver.',
                'note' => 'Ask the buyer to broaden the audience or confirm publishing with a small audience. Publishing stays blocked until one of these happens.']);
        }

        return $this->json(['ok' => true, 'audience' => $this->audienceSummary($campaign), 'estimate' => $sizer->describe($size),
            'note' => 'Audience kept.']);
    }

    private function offerAudienceMenu(Campaign $campaign, ?string $lead = null): string
    {
        $facets = (array) ($campaign->audience['linkedin_facets'] ?? []);
        $excludedCount = count($this->filterValues((array) ($campaign->audience['linkedin_exclusions'] ?? [])));
        $hasFilters = $facets !== [] || $excludedCount > 0;
        $sizer = app(LinkedInAudienceSize::class);
        $summary = $this->audienceSummary($campaign);
        $estimate = $sizer->describe($sizer->current($campaign));
        $small = $sizer->needsConfirmation($campaign);
        $options = [];
        if ($small) {
            $options[] = ['value' => 'confirm_small_audience', 'label' => 'Publish anyway with a small audience',
                'hint' => 'LinkedIn may not deliver below 300 members.', 'sends' => 'Use LinkedIn audience mode confirm_small_audience'];
        }
        if ($hasFilters) {
            $options[] = ['value' => 'done', 'label' => 'Keep this audience', ...$small ? [] : ['badge' => 'Suggested'],
                'sends' => 'Use LinkedIn audience mode done'];
        }
        foreach (['broad', 'retargeting', ...LinkedInTargetingFacets::keys()] as $value) {
            $count = count((array) ($facets[$value] ?? []));
            $options[] = [
                'value' => $value,
                'label' => match ($value) {
                    'broad' => $hasFilters ? 'Broad (clear all filters)' : 'Broad',
                    'retargeting' => 'Retargeting',
                    default => LinkedInTargetingFacets::label($value),
                },
                ...$count > 0 ? ['hint' => $count.' selected, add more'] : [],
                'sends' => 'Use LinkedIn audience mode '.$value,
            ];
        }
        $options[] = ['value' => 'exclude', 'label' => 'Exclude people',
            'hint' => $excludedCount > 0 ? $excludedCount.' excluded, add more' : 'Any LinkedIn attribute that can be excluded. Age, gender, and member groups cannot.',
            'sends' => 'Use LinkedIn audience mode exclude'];
        if ($hasFilters) {
            $options[] = ['value' => 'remove', 'label' => 'Remove a filter', 'sends' => 'Use LinkedIn audience mode remove'];
        }
        $question = trim(($lead ?? '').' '.(! $hasFilters ? 'Choose the LinkedIn audience refinement.' : 'Add another filter, remove one, or keep this audience.')
            .($summary !== '' ? ' Current audience: '.$summary.'.' : '')
            .($estimate !== null ? ' Estimated reach: '.$estimate.'.' : ''));
        $this->choices->offer('linkedin_audience_mode', $question, $options);

        return $this->json(['ok' => true, 'audience' => $summary, 'estimate' => $estimate,
            'note' => 'Let the user add professional filters one at a time, exclude people, remove a filter, keep the audience, use retargeting, or choose broad targeting.']);
    }

    private function audienceSummary(Campaign $campaign): string
    {
        $labels = (array) ($campaign->meta['linkedin_audience_labels'] ?? []);
        $parts = [];
        foreach ((array) ($campaign->audience['linkedin_facets'] ?? []) as $facet => $urns) {
            $parts[] = LinkedInTargetingFacets::label((string) $facet).': '.implode(', ', array_map(fn (string $urn): string => $labels[$urn] ?? $urn, (array) $urns));
        }
        foreach ((array) ($campaign->audience['linkedin_exclusions'] ?? []) as $facet => $urns) {
            $parts[] = 'Excluding '.LinkedInTargetingFacets::label((string) $facet).': '.implode(', ', array_map(fn (string $urn): string => $labels[$urn] ?? $urn, (array) $urns));
        }
        $segments = (array) ($campaign->targetingSet?->options['linkedin_segments'] ?? []);
        if ($segments !== []) {
            $parts[] = 'Retargeting: '.count($segments).' segment'.(count($segments) === 1 ? '' : 's');
        }

        return implode('; ', $parts);
    }

    private function offerAudienceSearch(string $mode, ?string $question = null, bool $exclude = false): void
    {
        $label = mb_strtolower(LinkedInTargetingFacets::label($mode));
        $instruction = $exclude
            ? 'Suggest '.$label.' this campaign should not reach, based on the campaign and its landing page. Search those terms with choose_linked_in_resource using exclude_facet '.$mode.' and show verified LinkedIn matches for me to exclude.'
            : 'Suggest '.$label.' search terms based on this campaign and its landing page. Search those terms with choose_linked_in_resource in audience mode '.$mode.' and show verified LinkedIn matches for me to select.';
        $this->choices->offer(
            field: 'retry_linkedin_audience',
            question: $question ?? 'How would you like to find LinkedIn '.$label.($exclude ? ' to exclude' : '').'?',
            options: [[
                'value' => 'ai_generated', 'label' => 'AI Generated', 'badge' => 'Suggested',
                'hint' => 'Suggest relevant '.$label.' '.($exclude ? 'to exclude' : 'for this campaign').'.',
                'sends' => $instruction.' Do not invent targeting URNs or select matches automatically.',
            ]],
            allowOther: true,
            otherLabel: 'Enter it myself',
            otherHint: 'Enter '.$label.' to search for'.($exclude ? ' and exclude' : '').'.',
            otherPlaceholder: LinkedInTargetingFacets::placeholder($mode) ?: 'e.g. Software Engineer',
        );
    }
}
