<?php

namespace App\Campaigns\Targeting;

use App\Agent\Choices;
use App\Agent\Workspace;
use App\Models\ArtifactFieldSource;
use App\Models\Campaign;
use App\Services\Meta\Meta;
use App\Services\Meta\MetaTargetingCatalog;
use RuntimeException;
use Throwable;

/**
 * Demographics, interests and behaviors for a draft Meta campaign.
 *
 * Selections are Meta's own ids. A different targeting type narrows the
 * audience (someone must match each type) and has to be kept before the
 * audience step is finished. Values inside one type are alternatives.
 */
class MetaDetailedTargeting
{
    /** Enough targets to leave this step. More suggestions are not offered past this. */
    private const MAX_TARGETS = 4;

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

    public function offerGroup(Campaign $campaign, string $group): string
    {
        if ($refused = $this->guard($campaign)) {
            return $refused;
        }

        if (! MetaTargetingCatalog::isGroup($group)) {
            return $this->json(['ok' => false, 'error' => 'Choose demographics, interests, or behaviors.']);
        }

        if (in_array($group, ['demographics', 'interests', 'behaviors'], true)) {
            return $this->offerBrowseSubcategories($campaign, $group);
        }

        $categories = MetaTargetingCatalog::categories($group);
        $this->choices->offer(
            field: 'meta_audience_category',
            question: 'Which '.MetaTargetingCatalog::groupLabel($group).' should this audience use?',
            options: array_map(fn (array $category, string $key): array => [
                'value' => $key,
                'label' => $category['label'],
                'hint' => MetaTargetingCatalog::categoryHint($category),
                'sends' => 'Use Meta '.MetaTargetingCatalog::groupLabel($group).' category '.$category['label'].'.',
            ], $categories, array_keys($categories)),
        );

        return $this->json(['ok' => true, 'note' => 'Category choices are on screen. Wait for the user.']);
    }

    public function offerCategory(Campaign $campaign, string $category): string
    {
        if ($refused = $this->guard($campaign)) {
            return $refused;
        }

        if (str_starts_with($category, 'browse|')) {
            return $this->offerBrowseOptions($campaign, $category);
        }

        $node = MetaTargetingCatalog::category($category);

        if ($node === null) {
            return $this->json(['ok' => false, 'error' => 'Choose a Meta audience category from the list.']);
        }

        if (count($node['facets']) === 1) {
            return $this->openFacet($campaign, $node['facets'][0], '');
        }

        $this->choices->offer(
            field: 'meta_audience_facet',
            question: 'Which '.$node['label'].' detail should this audience use?',
            options: array_map(fn (string $facet): array => [
                'value' => $facet,
                'label' => MetaTargetingCatalog::label($facet),
                'sends' => 'Use Meta audience facet '.MetaTargetingCatalog::label($facet).'.',
            ], $node['facets']),
        );

        return $this->json(['ok' => true, 'note' => 'Detail choices are on screen. Wait for the user.']);
    }

    public function openFacet(Campaign $campaign, string $facet, string $query): string
    {
        if ($refused = $this->guard($campaign)) {
            return $refused;
        }

        $facet = $facet !== '' ? $facet : (string) ($campaign->meta['meta_audience_facet'] ?? '');

        if (str_starts_with($facet, 'browse|')) {
            return $this->searchBrowse($campaign, $facet, $query);
        }

        $definition = MetaTargetingCatalog::facet($facet);

        if ($definition === null) {
            return $this->json(['ok' => false, 'error' => 'Choose a Meta audience detail from the list.']);
        }

        $campaign->update(['meta' => [...(array) $campaign->meta, 'meta_audience_facet' => $facet]]);

        if (! $definition['searchable']) {
            return $this->offerFixed($facet, $definition);
        }

        if (trim($query) === '' && ($definition['direct'] ?? false) === true) {
            $query = $definition['query'];
        }

        if (trim($query) === '') {
            return $this->offerSearch($definition);
        }

        return $this->offerMatches($campaign, $definition, $query);
    }

    /** @param  list<string>  $tokens */
    public function save(Campaign $campaign, array $tokens): string
    {
        if ($refused = $this->guard($campaign)) {
            return $refused;
        }

        $tokens = array_values(array_unique(array_map('strval', $tokens)));
        $offered = collect($this->workspace->pendingChoices())->first(
            fn (array $choice): bool => ($choice['field'] ?? null) === 'meta_detailed_selection'
                && (string) ($choice['focus_id'] ?? '') === (string) $campaign->getKey(),
        );
        $offeredIds = array_column($offered['options'] ?? [], 'value');

        if ($tokens === [] || array_diff($tokens, $offeredIds) !== []) {
            return $this->json(['ok' => false, 'error' => 'Choose targeting from the current Meta results.']);
        }

        $grouped = [];

        foreach ($tokens as $token) {
            if (! preg_match('/^([a-z_]+)\|(.+)$/D', $token, $matches)) {
                return $this->json(['ok' => false, 'error' => 'Choose targeting from the current Meta results.']);
            }

            $grouped[$matches[1]][] = $matches[2];
        }

        try {
            $selected = $this->selected($campaign);
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        foreach ($grouped as $field => $ids) {
            $browseType = (string) ($campaign->meta['meta_audience_browse_type'] ?? '');
            $facet = (string) ($campaign->meta['meta_audience_facet'] ?? '');
            $definition = str_starts_with($facet, 'browse|')
                ? null
                : MetaTargetingCatalog::facet($facet);

            if ($definition === null && $this->acceptsBrowseField($browseType, $field)) {
                $definition = [
                    'label' => MetaTargetingCatalog::fieldLabel($field),
                    'field' => $field,
                    'limit' => $field,
                    'shape' => 'object',
                ];
            }

            if ($definition === null || $definition['field'] !== $field) {
                return $this->json(['ok' => false, 'error' => 'Choose targeting from the current Meta results.']);
            }

            try {
                $verified = $this->verify($campaign, $definition, $ids);
            } catch (RuntimeException $exception) {
                return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
            }

            $existing = array_values((array) ($selected[$field] ?? []));
            $existingIds = array_column($existing, 'id');
            $room = max(0, self::MAX_TARGETS - $this->targetCount($selected));
            $additions = collect($verified)
                ->reject(fn (array $item): bool => in_array($item['id'], $existingIds, true))
                ->take($room)
                ->values()
                ->all();
            $merged = [...$existing, ...$additions];

            if (count($merged) > MetaTargetingCatalog::MAX_PER_FIELD) {
                return $this->json(['ok' => false, 'error' => 'Choose no more than '.MetaTargetingCatalog::MAX_PER_FIELD.' '.MetaTargetingCatalog::fieldLabel($field).'.']);
            }

            $selected[$field] = $merged;
        }

        $finished = $this->persist($campaign, $selected);

        return $this->json([
            'ok' => true,
            'selected' => $selected,
            'note' => $finished
                ? 'Audience saved with '.self::MAX_TARGETS.' targets at most. Offer Keep this audience and wait for that choice. Do not offer more targets and do not continue to the next campaign step.'
                : 'The selected Meta targeting is saved. Add another filter, remove one, or keep this audience.',
        ]);
    }

    public function offerRemoval(Campaign $campaign): string
    {
        if ($refused = $this->guard($campaign)) {
            return $refused;
        }

        try {
            $selected = $this->selected($campaign);
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        $options = [];

        foreach ($selected as $field => $items) {
            foreach ($items as $item) {
                $options[] = [
                    'value' => $field.'|'.$item['id'],
                    'label' => MetaTargetingCatalog::fieldLabel($field).': '.$item['name'],
                    'sends' => 'Remove '.$item['name'].' from the Meta audience.',
                ];
            }
        }

        if ($options === []) {
            return $this->json(['ok' => false, 'error' => 'There is no detailed targeting to remove.']);
        }

        $this->choices->offer(
            field: 'meta_detailed_remove',
            question: 'Which targeting should be removed? Everything else is kept.',
            options: $options,
            multiple: true,
        );

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

    /** @param  list<string>  $tokens */
    public function remove(Campaign $campaign, array $tokens): string
    {
        if ($refused = $this->guard($campaign)) {
            return $refused;
        }

        $tokens = array_values(array_unique(array_map('strval', $tokens)));

        try {
            $selected = $this->selected($campaign);
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        $known = [];

        foreach ($selected as $field => $items) {
            foreach ($items as $item) {
                $known[] = $field.'|'.$item['id'];
            }
        }

        if ($tokens === [] || array_diff($tokens, $known) !== []) {
            return $this->json(['ok' => false, 'error' => 'Choose saved targeting to remove.']);
        }

        foreach ($tokens as $token) {
            [$field, $id] = explode('|', $token, 2);
            $selected[$field] = array_values(array_filter(
                $selected[$field] ?? [],
                fn (array $item): bool => $item['id'] !== $id,
            ));

            if ($selected[$field] === []) {
                unset($selected[$field]);
            }
        }

        $this->persist($campaign, $selected, 'Those selections were removed.', syncInterests: true);

        return $this->json(['ok' => true, 'selected' => $selected, 'note' => 'The Meta audience was updated.']);
    }

    public function keep(Campaign $campaign): string
    {
        if ($refused = $this->guard($campaign)) {
            return $refused;
        }

        try {
            $selected = $this->selected($campaign);
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        if ($selected === []) {
            return $this->json(['ok' => false, 'error' => 'Choose targeting before keeping this audience.']);
        }

        $audience = (array) $campaign->audience;
        $audience['meta_audience_mode'] = 'custom';
        $campaign->update([
            'audience' => $audience,
            'meta' => [...(array) $campaign->meta, 'meta_audience_reviewed' => true],
        ]);
        $this->workspace->recordSource(
            $campaign,
            'audience',
            $this->workspace->wasOffered('meta_audience_mode')
                ? ArtifactFieldSource::USER_STATED
                : ArtifactFieldSource::MODEL_INFERRED,
        );

        return $this->json([
            'ok' => true,
            'audience' => $this->summary($campaign->fresh()),
            'note' => 'Meta audience kept. Continue to the next campaign step.',
        ]);
    }

    public function hasNarrowing(Campaign $campaign): bool
    {
        try {
            $stored = $this->stored($campaign);
        } catch (RuntimeException) {
            return true;
        }

        foreach ($stored as $field => $items) {
            if ($field !== 'interests' && $items !== []) {
                return true;
            }
        }

        return false;
    }

    public function summary(Campaign $campaign): string
    {
        try {
            $selected = $this->selected($campaign);
        } catch (RuntimeException) {
            return 'Saved targeting needs review.';
        }

        $parts = [];

        foreach ($selected as $field => $items) {
            $parts[] = MetaTargetingCatalog::fieldLabel($field).': '.implode(', ', array_column($items, 'name'));
        }

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

    /**
     * Saved detailed targeting other than interests, re-checked with Meta.
     *
     * Interests stay on the existing interest check. Device and operating
     * system names are confirmed by searching them again, because Meta does
     * not validate those through the interest validation call.
     *
     * @return array<string, list<array{id: string, name: string}>>
     */
    public function verifiedForPublish(Campaign $campaign): array
    {
        $selected = $this->stored($campaign);
        unset($selected['interests']);

        if ($selected === []) {
            return [];
        }

        if ((array) ($campaign->special_ad_categories ?? []) !== ['NONE']) {
            throw new RuntimeException('Meta detailed targeting is unavailable for this declared special ad category.');
        }

        $verified = [];

        foreach ($selected as $field => $items) {
            $definition = $this->definitionForField($field);
            $verified[$field] = $this->verify($campaign, $definition, array_column($items, 'id'));
        }

        return $verified;
    }

    /**
     * @return array<string, list<array{id: string, name: string}>>
     */
    public function selected(Campaign $campaign): array
    {
        $selected = $this->stored($campaign);
        $interests = $campaign->audience['meta_interests'] ?? [];

        if ($interests === [] || $interests === null) {
            return $selected;
        }

        if (! is_array($interests) || ! array_is_list($interests)) {
            throw new RuntimeException('Saved Meta interests are invalid. Search and select them again.');
        }

        $normalized = [];

        foreach ($interests as $interest) {
            $id = is_array($interest) ? (string) ($interest['id'] ?? '') : '';
            $name = is_array($interest) ? trim((string) ($interest['name'] ?? '')) : '';

            if (preg_match('/^[0-9]+$/D', $id) !== 1 || $name === '') {
                throw new RuntimeException('Saved Meta interests are invalid. Search and select them again.');
            }

            $normalized[] = ['id' => $id, 'name' => $name];
        }

        $selected['interests'] = collect([...(array) ($selected['interests'] ?? []), ...$normalized])
            ->unique(fn (array $item): string => $item['id'])
            ->values()
            ->all();

        return $selected;
    }

    /**
     * @param  array<string, list<array{id: string, name: string}>>  $selected
     */
    private function persist(Campaign $campaign, array $selected, ?string $lead = null, bool $syncInterests = false): bool
    {
        $audience = (array) $campaign->audience;
        $interests = array_values($selected['interests'] ?? []);
        $touchesInterests = $syncInterests || array_key_exists('interests', $selected);
        unset($selected['interests']);
        $selected = array_filter($selected, fn (array $items): bool => $items !== []);

        if ($touchesInterests) {
            if ($interests === []) {
                unset($audience['meta_interests']);
            } else {
                $audience['meta_interests'] = $interests;
                $audience['meta_audience_mode'] = 'custom';
            }
        }

        if ($selected === []) {
            unset($audience['meta_detailed']);
        } else {
            $audience['meta_detailed'] = $selected;
            $audience['meta_audience_mode'] = 'custom';
        }

        $targetCount = $this->targetCount([
            ...$selected,
            'interests' => $touchesInterests ? $interests : (array) ($audience['meta_interests'] ?? []),
        ]);
        $finished = $targetCount >= 3;
        $reviewed = $selected === []
            ? (bool) ($campaign->meta['meta_audience_reviewed'] ?? false)
            : false;

        $campaign->update([
            'audience' => $audience,
            'meta' => [...(array) $campaign->meta, 'meta_audience_reviewed' => $reviewed],
        ]);
        $this->workspace->recordSource(
            $campaign,
            'audience',
            $this->workspace->wasOffered('meta_detailed_selection') || $this->workspace->wasOffered('meta_detailed_remove')
                ? ArtifactFieldSource::USER_STATED
                : ArtifactFieldSource::MODEL_INFERRED,
        );
        $fresh = $campaign->fresh();
        $this->offerContinuation($fresh, $lead);

        if (! $finished) {
            $this->offerSuggestions($fresh);
        }

        return $finished;
    }

    private function offerContinuation(Campaign $campaign, ?string $lead): void
    {
        $summary = $this->summary($campaign);
        $options = [];

        $atCap = false;

        try {
            $atCap = $this->targetCount($this->selected($campaign)) >= 3;
        } catch (RuntimeException) {
            $atCap = false;
        }

        if ($summary !== '' && $summary !== 'Saved targeting needs review.') {
            $options[] = [
                'value' => 'done',
                'label' => 'Keep this audience',
                'badge' => 'Suggested',
                'sends' => 'Keep this Meta audience.',
            ];
        }

        if ($atCap) {
            if ($summary !== '' && $summary !== 'Saved targeting needs review.') {
                $options[] = [
                    'value' => 'remove',
                    'label' => 'Remove a selection',
                    'sends' => 'Remove Meta audience targeting.',
                ];
            }

            $this->choices->offer(
                field: 'meta_audience_mode',
                question: trim(($lead ? $lead.' ' : '').'Keep this audience to continue. Current audience: '.$summary.'.'),
                options: $options,
            );

            return;
        }

        foreach (MetaTargetingCatalog::groups() as $group) {
            $options[] = [
                'value' => $group,
                'label' => 'Add '.MetaTargetingCatalog::groupLabel($group),
                'sends' => 'Refine the Meta audience with '.strtolower(MetaTargetingCatalog::groupLabel($group)).'.',
            ];
        }

        $options[] = [
            'value' => 'broad',
            'label' => 'Broad audience',
            'hint' => 'Clears detailed targeting and reaches the selected age and gender.',
            'sends' => 'Use broad Meta audience targeting.',
        ];

        if ($summary !== '' && $summary !== 'Saved targeting needs review.') {
            $options[] = [
                'value' => 'remove',
                'label' => 'Remove a selection',
                'sends' => 'Remove Meta audience targeting.',
            ];
        }

        $this->choices->offer(
            field: 'meta_audience_mode',
            question: trim(($lead ? $lead.' ' : '').($summary !== ''
                ? 'Add another filter, remove one, or keep this audience. Current audience: '.$summary.'.'
                : 'Choose the Meta audience.')),
            options: $options,
        );
    }

    /**
     * @param  array{label: string, field: string, searchable: bool, query: string, shape: string}  $definition
     */
    private function offerFixed(string $facet, array $definition): string
    {
        $options = MetaTargetingCatalog::options($facet);

        if ($options === []) {
            return $this->json(['ok' => false, 'error' => 'Meta has no fixed list for '.MetaTargetingCatalog::label($facet).'.']);
        }

        $this->choices->offer(
            field: 'meta_detailed_selection',
            question: 'Choose the '.strtolower(MetaTargetingCatalog::label($facet)).' to include.',
            options: array_map(fn (array $option): array => [
                'value' => $definition['field'].'|'.$option['id'],
                'label' => $option['name'],
                'sends' => 'Include '.$option['name'].'.',
            ], $options),
            multiple: true,
        );

        return $this->json(['ok' => true, 'note' => 'Meta options are on screen. Wait for the user to select them.']);
    }

    /** @param  array{label: string, query: string}  $definition */
    private function offerSearch(array $definition): string
    {
        $label = strtolower($definition['label']);
        $this->choices->offer(
            field: 'retry_meta_audience',
            question: 'How would you like to find '.$label.'?',
            options: [[
                'value' => 'ai_generated',
                'label' => 'AI Generated',
                'badge' => 'Suggested',
                'hint' => 'Suggest relevant '.$label.' for this campaign.',
                'sends' => 'Suggest '.$label.' search terms based on this campaign and its landing page. Search those terms with set_targeting facet_query and show verified Meta matches for me to select. Do not invent targeting IDs or select matches automatically.',
            ]],
            allowOther: true,
            otherLabel: 'Enter it myself',
            otherHint: 'Search Meta for '.$label.'.',
            otherPlaceholder: 'e.g. '.$definition['query'],
            otherValue: $definition['query'],
        );

        return $this->json(['ok' => true, 'note' => 'Ask which '.$label.' to search for. Do not invent Meta targeting ids.']);
    }

    /**
     * @param  array{label: string, field: string, limit: string, shape: string}  $definition
     */
    private function offerMatches(Campaign $campaign, array $definition, string $query): string
    {
        $terms = $this->terms($query);

        if ($terms === []) {
            return $this->json(['ok' => false, 'error' => 'Enter up to five search terms.']);
        }

        if (blank($campaign->ad_account_id)) {
            return $this->json(['ok' => false, 'error' => 'Select a Meta ad account before searching audience targeting.']);
        }

        try {
            $matches = collect($terms)->flatMap(fn (string $term): array => $this->meta->targetingSearch(
                (string) $campaign->ad_account_id,
                $term,
                $definition['limit'],
            ))->map(fn (array $match): ?array => $this->normaliseMatch($match, $definition['shape']))
                ->filter()
                ->unique(fn (array $match): string => $match['id'])
                ->take(25)
                ->values();
        } catch (RuntimeException $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        if ($matches->isEmpty()) {
            return $this->json(['ok' => false, 'error' => 'Meta found no matching '.strtolower($definition['label']).'. Try a shorter term. Some options are unavailable on this account.']);
        }

        $this->choices->offer(
            field: 'meta_detailed_selection',
            question: 'Choose the '.strtolower($definition['label']).' to include.',
            options: $matches->map(function (array $match) use ($definition): array {
                $path = collect($match['path'])
                    ->reject(fn (string $part): bool => strcasecmp($part, $match['name']) === 0)
                    ->implode(' · ');

                return [
                    'value' => $definition['field'].'|'.$match['id'],
                    'label' => $match['name'],
                    'hint' => $path !== '' ? $path : null,
                    'sends' => 'Include '.$match['name'].'.',
                ];
            })->all(),
            multiple: true,
        );

        return $this->json(['ok' => true, 'ideas' => $terms, 'note' => 'Meta matches are on screen. Wait for the user to select them.']);
    }

    /**
     * @param  array{field: string, limit: string, shape: string, label: string}  $definition
     * @param  list<string>  $ids
     * @return list<array{id: string, name: string}>
     */
    private function verify(Campaign $campaign, array $definition, array $ids): array
    {
        if (blank($campaign->ad_account_id)) {
            throw new RuntimeException('Select a Meta ad account before saving audience targeting.');
        }

        $ids = array_values(array_unique($ids));

        if ($definition['shape'] === 'device') {
            return $this->verifyDevices($campaign, $definition, $ids);
        }

        if ($ids === [] || collect($ids)->contains(fn (string $id): bool => preg_match('/^[0-9]+$/D', $id) !== 1)) {
            throw new RuntimeException('Choose targeting from the current Meta results.');
        }

        $validated = collect($this->meta->validateTargetingOptions((string) $campaign->ad_account_id, $definition['limit'], $ids))
            ->keyBy(fn (array $row): string => (string) ($row['id'] ?? ''));
        $verified = [];

        foreach ($ids as $id) {
            $row = $validated->get($id);

            if (! is_array($row) || ($row['valid'] ?? false) !== true || blank($row['name'] ?? null)) {
                throw new RuntimeException('A selected Meta targeting option is no longer available. Search again before choosing it.');
            }

            $verified[] = ['id' => $id, 'name' => (string) $row['name']];
        }

        return $verified;
    }

    /**
     * @param  array{limit: string, label: string}  $definition
     * @param  list<string>  $ids
     * @return list<array{id: string, name: string}>
     */
    private function verifyDevices(Campaign $campaign, array $definition, array $ids): array
    {
        $verified = [];

        foreach ($ids as $id) {
            if (preg_match('/^[\pL\pN ._\x27&()+-]{2,80}$/uD', $id) !== 1) {
                throw new RuntimeException('Choose a device or operating system from the current Meta results.');
            }

            $found = collect($this->meta->targetingSearch((string) $campaign->ad_account_id, $id, $definition['limit']))
                ->map(fn (array $match): ?array => $this->normaliseMatch($match, 'device'))
                ->filter()
                ->first(fn (array $match): bool => strcasecmp($match['name'], $id) === 0);

            if ($found === null) {
                throw new RuntimeException('A selected device or operating system is no longer available. Search again before choosing it.');
            }

            $verified[] = ['id' => $found['name'], 'name' => $found['name']];
        }

        return $verified;
    }

    /**
     * @return array{id: string, name: string, path: list<string>}|null
     */
    private function normaliseMatch(array $match, string $shape): ?array
    {
        $name = trim((string) ($match['name'] ?? ''));
        $id = trim((string) ($match['id'] ?? ''));

        if ($shape === 'device') {
            $id = $name;
        }

        if ($name === '' || ($shape !== 'device' && preg_match('/^[0-9]+$/D', $id) !== 1)) {
            return null;
        }

        return [
            'id' => $id,
            'name' => $name,
            'path' => array_values(array_filter(array_map(
                fn (mixed $part): string => trim((string) $part),
                (array) ($match['path'] ?? []),
            ))),
        ];
    }

    /**
     * @return array<string, list<array{id: string, name: string}>>
     */
    private function stored(Campaign $campaign): array
    {
        $stored = $campaign->audience['meta_detailed'] ?? [];

        if ($stored === [] || $stored === null) {
            return [];
        }

        if (! is_array($stored) || array_is_list($stored)) {
            throw new RuntimeException('Saved Meta targeting is invalid. Search and select it again.');
        }

        $selected = [];

        foreach ($stored as $field => $items) {
            if (! is_string($field) || $this->definitionForField($field) === [] || ! is_array($items) || ! array_is_list($items)) {
                throw new RuntimeException('Saved Meta targeting is invalid. Search and select it again.');
            }

            $normalized = [];

            foreach ($items as $item) {
                $id = is_array($item) ? trim((string) ($item['id'] ?? '')) : '';
                $name = is_array($item) ? trim((string) ($item['name'] ?? '')) : '';
                $numeric = preg_match('/^[0-9]+$/D', $id) === 1;
                $device = in_array($field, ['user_device', 'user_os'], true)
                    && preg_match('/^[\pL\pN ._\x27&()+-]{2,80}$/uD', $id) === 1;

                if ($name === '' || (! $numeric && ! $device)) {
                    throw new RuntimeException('Saved Meta targeting is invalid. Search and select it again.');
                }

                $normalized[] = ['id' => $id, 'name' => $name];
            }

            if ($normalized !== []) {
                $selected[$field] = $normalized;
            }
        }

        return $selected;
    }

    /**
     * @return array{field: string, limit: string, shape: string, label: string}
     */
    private function definitionForField(string $field): array
    {
        $match = collect(MetaTargetingCatalog::groups())
            ->flatMap(fn (string $group): array => MetaTargetingCatalog::categories($group))
            ->flatMap(fn (array $category): array => $category['facets'])
            ->map(fn (string $facet): ?array => MetaTargetingCatalog::facet($facet))
            ->first(fn (?array $facet): bool => ($facet['field'] ?? null) === $field);

        if (! is_array($match)) {
            if ($field !== 'income') {
                return [];
            }

            return [
                'label' => MetaTargetingCatalog::fieldLabel($field),
                'field' => $field,
                'limit' => $field,
                'shape' => 'object',
            ];
        }

        return $match;
    }

    /** @return list<string> */
    private function terms(string $ideas): array
    {
        $parts = preg_split('/[,;\n]+/u', $ideas, 6, PREG_SPLIT_NO_EMPTY) ?: [];
        $terms = [];

        foreach (array_slice($parts, 0, 5) as $part) {
            $term = trim($part, " \t\n\r\0\x0B.,!?-");

            if (mb_strlen($term) >= 2 && mb_strlen($term) <= 80) {
                $terms[] = $term;
            }
        }

        return array_values(array_unique($terms));
    }

    private function acceptsBrowseField(string $browseType, string $field): bool
    {
        if ($browseType === '' || $field === '') {
            return false;
        }

        if ($field === $browseType) {
            return true;
        }

        return $browseType === 'demographics' && in_array($field, [
            'life_events', 'family_statuses', 'industries', 'education_statuses',
            'education_majors', 'education_schools', 'work_employers', 'work_positions',
            'relationship_statuses', 'income', 'behaviors', 'interests',
        ], true);
    }

    private function offerBrowseSubcategories(Campaign $campaign, string $group): string
    {
        if (blank($campaign->ad_account_id)) {
            return $this->json(['ok' => false, 'error' => 'Select a Meta ad account before browsing audience targeting.']);
        }

        try {
            $rows = $this->meta->targetingBrowse((string) $campaign->ad_account_id, $group);
        } catch (Throwable $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        $subcategories = $this->browseSubcategories($rows);

        if ($subcategories === []) {
            return $this->json(['ok' => false, 'error' => 'Meta returned no '.MetaTargetingCatalog::groupLabel($group).' categories for this ad account.']);
        }

        $this->choices->offer(
            field: 'meta_audience_category',
            question: 'Which '.MetaTargetingCatalog::groupLabel($group).' should this audience use?',
            options: array_map(function (string $name, array $items) use ($group): array {
                $leaves = $this->browseLeaves($items);

                return [
                    'value' => 'browse|'.$group.'|'.rawurlencode($name),
                    'label' => $name,
                    'hint' => count($leaves).' options from Meta',
                    'sends' => 'Use Meta '.MetaTargetingCatalog::groupLabel($group).' category '.$name.'.',
                ];
            }, array_keys($subcategories), $subcategories),
        );

        return $this->json(['ok' => true, 'note' => 'Meta categories are on screen. Wait for the user.']);
    }

    private function offerBrowseOptions(Campaign $campaign, string $category): string
    {
        $parts = explode('|', $category, 3);
        $limitType = $parts[1] ?? '';
        $name = rawurldecode($parts[2] ?? '');

        if (! in_array($limitType, ['demographics', 'interests', 'behaviors'], true) || $name === '') {
            return $this->json(['ok' => false, 'error' => 'Choose a Meta audience category from the list.']);
        }

        if (blank($campaign->ad_account_id)) {
            return $this->json(['ok' => false, 'error' => 'Select a Meta ad account before browsing audience targeting.']);
        }

        try {
            $rows = $this->browseSubcategories($this->meta->targetingBrowse((string) $campaign->ad_account_id, $limitType))[$name] ?? [];
        } catch (Throwable $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        $leaves = array_slice($this->browseLeaves($rows), 0, 30);

        if ($leaves === []) {
            return $this->json(['ok' => false, 'error' => 'Meta returned no options under '.$name.'.']);
        }

        $campaign->update(['meta' => [
            ...(array) $campaign->meta,
            'meta_audience_facet' => 'browse|'.$limitType,
            'meta_audience_browse_type' => $limitType,
            'meta_audience_browse_subcategory' => $name,
        ]]);

        $options = [];

        foreach ($leaves as $row) {
            $label = (string) $row['name'];
            $type = (string) ($row['type'] ?? $limitType);

            if (! MetaTargetingCatalog::acceptsLimit($type)) {
                $type = $limitType;
            }

            if (! $this->acceptsBrowseField($limitType, $type) || ! MetaTargetingCatalog::acceptsLimit($type)) {
                continue;
            }

            $options[] = [
                'value' => $type.'|'.$row['id'],
                'label' => $label,
                'hint' => isset($row['audience_size_lower_bound'])
                    ? 'About '.number_format((int) $row['audience_size_lower_bound']).'+ people'
                    : null,
                'sends' => 'Include '.$label.'.',
            ];
        }

        if ($options === []) {
            return $this->json(['ok' => false, 'error' => 'Meta returned no selectable options under '.$name.'.']);
        }

        $this->choices->offer(
            field: 'meta_detailed_selection',
            question: 'Choose the '.$name.' targets Meta currently offers.',
            options: $options,
            multiple: true,
        );

        return $this->json(['ok' => true, 'note' => 'Meta options are on screen. Wait for the user to select them. Search with facet_query if the option is not listed.']);
    }

    private function searchDemographicCategories(Campaign $campaign, string $query): string
    {
        $terms = $this->terms($query);

        if ($terms === []) {
            return $this->json(['ok' => false, 'error' => 'Enter up to five search terms.']);
        }

        if (blank($campaign->ad_account_id)) {
            return $this->json(['ok' => false, 'error' => 'Select a Meta ad account before searching audience targeting.']);
        }

        try {
            $rows = $this->browseLeaves($this->meta->targetingBrowse((string) $campaign->ad_account_id, 'demographics'));
        } catch (Throwable $exception) {
            return $this->json(['ok' => false, 'error' => $exception->getMessage()]);
        }

        $needles = array_map(mb_strtolower(...), $terms);
        $options = [];

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

            if ($name === '' || preg_match('/^[0-9]+$/D', $id) !== 1 || ! $this->acceptsBrowseField('demographics', $type) || ! MetaTargetingCatalog::acceptsLimit($type)) {
                continue;
            }

            $haystack = mb_strtolower($name);

            if (! collect($needles)->contains(fn (string $needle): bool => str_contains($haystack, $needle))) {
                continue;
            }

            $options[] = [
                'value' => $type.'|'.$id,
                'label' => $name,
                'sends' => 'Include '.$name.'.',
            ];

            if (count($options) === 25) {
                break;
            }
        }

        if ($options === []) {
            return $this->json(['ok' => false, 'error' => 'Meta found no matching demographics. Try a shorter term. Some options are unavailable on this account.']);
        }

        $this->choices->offer(
            field: 'meta_detailed_selection',
            question: 'Choose the demographics to include.',
            options: $options,
            multiple: true,
        );

        return $this->json(['ok' => true, 'note' => 'Meta options are on screen. Wait for the user to select them.']);
    }

    private function searchBrowse(Campaign $campaign, string $facet, string $query): string
    {
        $limitType = explode('|', $facet, 2)[1] ?? '';

        if (! in_array($limitType, ['demographics', 'interests', 'behaviors'], true)) {
            return $this->json(['ok' => false, 'error' => 'Choose a Meta audience detail from the list.']);
        }

        $campaign->update(['meta' => [
            ...(array) $campaign->meta,
            'meta_audience_facet' => 'browse|'.$limitType,
            'meta_audience_browse_type' => $limitType,
        ]]);

        if (trim($query) === '') {
            $subcategory = (string) ($campaign->meta['meta_audience_browse_subcategory'] ?? '');

            if ($subcategory === '') {
                return $this->offerBrowseSubcategories($campaign, $limitType);
            }

            return $this->offerBrowseOptions($campaign, 'browse|'.$limitType.'|'.rawurlencode($subcategory));
        }

        if ($limitType === 'demographics') {
            return $this->searchDemographicCategories($campaign, $query);
        }

        return $this->offerMatches($campaign, [
            'label' => MetaTargetingCatalog::groupLabel($limitType),
            'field' => $limitType,
            'limit' => $limitType,
            'shape' => 'object',
        ], $query);
    }

    /**
     * @param  array<string, list<array<string, mixed>>>  $selected
     */
    private function targetCount(array $selected): int
    {
        $count = 0;

        foreach ($selected as $items) {
            if (is_array($items)) {
                $count += count($items);
            }
        }

        return $count;
    }

    private function offerSuggestions(Campaign $campaign): void
    {
        $type = (string) ($campaign->meta['meta_audience_browse_type'] ?? '');

        if ($type === '' || blank($campaign->ad_account_id)) {
            return;
        }

        try {
            $selected = $this->selected($campaign);
        } catch (RuntimeException) {
            return;
        }

        $list = array_slice(array_map(
            static fn (array $item): array => ['type' => $type, 'id' => $item['id']],
            array_values(array_filter(
                (array) ($selected[$type] ?? []),
                static fn (array $item): bool => preg_match('/^[0-9]+$/D', (string) ($item['id'] ?? '')) === 1,
            )),
        ), 0, 10);

        if ($list === [] || $this->targetCount($selected) >= 3) {
            return;
        }

        $room = self::MAX_TARGETS - $this->targetCount($selected);

        if ($room < 1) {
            return;
        }

        try {
            $rows = $this->meta->targetingSuggestions((string) $campaign->ad_account_id, $list);
        } catch (Throwable) {
            return;
        }

        $savedIds = array_column($list, 'id');
        $options = [];

        foreach ($rows as $row) {
            if (! is_array($row)) {
                continue;
            }

            $id = (string) ($row['id'] ?? '');
            $name = trim((string) ($row['name'] ?? ''));
            $rowType = (string) ($row['type'] ?? $type);

            if ($name === '' || preg_match('/^[0-9]+$/D', $id) !== 1 || in_array($id, $savedIds, true)) {
                continue;
            }

            if ($rowType !== '' && $rowType !== $type) {
                continue;
            }

            $options[] = [
                'value' => $type.'|'.$id,
                'label' => $name,
                'badge' => 'Suggested',
                'sends' => 'Include '.$name.'.',
            ];
        }

        if ($options === []) {
            return;
        }

        $this->choices->offer(
            field: 'meta_detailed_selection',
            question: 'Meta suggests these related targets. Add any that fit, up to '.$room.' more.',
            options: array_slice($options, 0, $room),
            multiple: true,
        );
    }

    /**
     * @param  list<array<string, mixed>>  $rows
     * @return array<string, list<array<string, mixed>>>
     */
    private function browseSubcategories(array $rows): array
    {
        $groups = [];

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

            if ($name === '' || preg_match('/^[0-9]+$/D', $id) !== 1) {
                continue;
            }

            $path = array_values(array_filter(array_map('strval', (array) ($row['path'] ?? []))));
            $subcategory = count($path) >= 2 ? $path[1] : $name;
            $groups[$subcategory][] = $row;
        }

        ksort($groups);

        return $groups;
    }

    /**
     * @param  list<array<string, mixed>>  $rows
     * @return list<array<string, mixed>>
     */
    private function browseLeaves(array $rows): array
    {
        $leaves = array_values(array_filter($rows, function (array $row): bool {
            $path = array_values(array_filter(array_map('strval', (array) ($row['path'] ?? []))));

            return count($path) !== 2;
        }));

        if ($leaves === []) {
            $leaves = $rows;
        }

        return array_values($leaves);
    }

    private function guard(Campaign $campaign): ?string
    {
        if ($campaign->platform !== 'meta' || $campaign->isPublished()
            || (array) ($campaign->special_ad_categories ?? []) !== ['NONE']) {
            return $this->json(['ok' => false, 'error' => 'Detailed audience targeting is available only for draft Meta campaigns without a declared special ad category.']);
        }

        return null;
    }

    /** @param  array<string, mixed>  $payload */
    private function json(array $payload): string
    {
        return json_encode($payload, JSON_UNESCAPED_SLASHES);
    }
}
