<?php

namespace App\Services\Meta;

use Illuminate\Support\Str;

/**
 * The Meta detailed-targeting tree a buyer can browse.
 *
 * Names follow the Ads Manager browse menu (May 2024). A name is a search,
 * not a Meta id: the result's own path says where Meta files it today, and a
 * leaf is omitted from publish when Meta no longer validates it.
 *
 * Education level and relationship status stay the numeric enums. Separated,
 * divorced, and widowed stay even though that browse snapshot left them out.
 * Facebook-access devices and operating systems are behaviors. The ad set's
 * own device and operating-system fields stay a separate category.
 */
class MetaTargetingCatalog
{
    public const MAX_PER_FIELD = 20;

    /**
     * Labels the chat and tests already address by a stable key.
     *
     * @var array<string, string>
     */
    private const RESERVED_KEYS = [
        'Parents with toddlers (aged 1-2)' => 'parents_with_children',
        'New job' => 'new_job_or_move',
        'Engaged shoppers' => 'engaged_shoppers',
        'Yoga' => 'yoga',
        'Current events (politics)' => 'news_and_events',
    ];

    /**
     * @var array<string, array{label: string, categories: array<string, array{label: string, facets: list<string>}>}>|null
     */
    private static ?array $groupMap = null;

    /** @var array<string, array{label: string, group: string, parent: string, field: string, limit: string, searchable: bool, query: string, shape: string, direct: bool}>|null */
    private static ?array $facets = null;

    /** @return list<string> */
    public static function groups(): array
    {
        self::boot();

        return array_keys(self::$groupMap ?? []);
    }

    public static function groupLabel(string $group): string
    {
        self::boot();

        return self::$groupMap[$group]['label'] ?? $group;
    }

    public static function isGroup(string $group): bool
    {
        self::boot();

        return isset(self::$groupMap[$group]);
    }

    /**
     * @return array<string, array{label: string, facets: list<string>}>
     */
    public static function categories(string $group): array
    {
        self::boot();

        return self::$groupMap[$group]['categories'] ?? [];
    }

    /**
     * @return array{label: string, facets: list<string>}|null
     */
    public static function category(string $key): ?array
    {
        self::boot();

        foreach (self::$groupMap ?? [] as $group) {
            if (isset($group['categories'][$key])) {
                return $group['categories'][$key];
            }
        }

        return null;
    }

    public static function exists(string $facet): bool
    {
        return isset(self::facets()[$facet]);
    }

    /**
     * @return array{label: string, group: string, parent: string, field: string, limit: string, searchable: bool, query: string, shape: string, direct: bool}|null
     */
    public static function facet(string $key): ?array
    {
        return self::facets()[$key] ?? null;
    }

    public static function label(string $facet): string
    {
        return self::facets()[$facet]['label'] ?? $facet;
    }

    public static function fieldLabel(string $field): string
    {
        return match ($field) {
            'interests' => 'Interests',
            'behaviors' => 'Behaviors',
            'education_statuses' => 'Education level',
            'education_majors' => 'Fields of study',
            'education_schools' => 'Schools',
            'work_employers' => 'Employers',
            'work_positions' => 'Job titles',
            'industries' => 'Industries',
            'relationship_statuses' => 'Relationship status',
            'family_statuses' => 'Family',
            'life_events' => 'Life events',
            'income' => 'Income',
            'user_device' => 'Devices',
            'user_os' => 'Operating systems',
            default => $field,
        };
    }

    /** @return list<string> */
    public static function limitTypes(): array
    {
        return array_values(array_unique(array_column(self::facets(), 'limit')));
    }

    public static function acceptsLimit(string $limit): bool
    {
        return in_array($limit, self::limitTypes(), true) || $limit === 'income';
    }

    /**
     * Fixed lists Meta does not search by name. Anything else is searched.
     *
     * @return list<array{id: string, name: string}>
     */
    public static function options(string $facet): array
    {
        return match ($facet) {
            'education_level' => [
                ['id' => '1', 'name' => 'In high school'],
                ['id' => '13', 'name' => 'Some high school'],
                ['id' => '4', 'name' => 'High school grad'],
                ['id' => '5', 'name' => 'Some college'],
                ['id' => '2', 'name' => 'In college'],
                ['id' => '6', 'name' => 'Associate degree'],
                ['id' => '3', 'name' => 'College grad'],
                ['id' => '7', 'name' => 'In grad school'],
                ['id' => '8', 'name' => 'Some grad school'],
                ['id' => '9', 'name' => "Master's degree"],
                ['id' => '10', 'name' => 'Professional degree'],
                ['id' => '11', 'name' => 'Doctorate degree'],
            ],
            'relationship_status' => [
                ['id' => '1', 'name' => 'Single'],
                ['id' => '2', 'name' => 'In a relationship'],
                ['id' => '4', 'name' => 'Engaged'],
                ['id' => '3', 'name' => 'Married'],
                ['id' => '11', 'name' => 'Separated'],
                ['id' => '12', 'name' => 'Divorced'],
                ['id' => '13', 'name' => 'Widowed'],
            ],
            default => [],
        };
    }

    /**
     * A short hint for a category card. Long browse lists stay searchable
     * on the next step instead of being pasted into the card.
     *
     * @param  array{facets: list<string>}  $category
     */
    public static function categoryHint(array $category): string
    {
        $labels = array_map(fn (string $facet): string => self::label($facet), $category['facets']);

        if (count($labels) <= 4) {
            return implode(', ', $labels);
        }

        return implode(', ', array_slice($labels, 0, 3)).', and '.(count($labels) - 3).' more';
    }

    /**
     * @return array<string, array{label: string, group: string, parent: string, field: string, limit: string, searchable: bool, query: string, shape: string, direct: bool}>
     */
    private static function facets(): array
    {
        self::boot();

        return self::$facets ?? [];
    }

    private static function boot(): void
    {
        if (self::$facets !== null && self::$groupMap !== null) {
            return;
        }

        $groups = [];
        $facets = [];

        foreach (MetaTargetingBrowse::tree() as $groupKey => $group) {
            $categories = [];

            foreach ($group['categories'] as $categoryKey => $category) {
                $facetKeys = [];

                foreach ($category['facets'] ?? [] as $facet) {
                    $facetKeys[] = $facet['key'];
                    $facets[$facet['key']] = self::leaf(
                        $facet['label'],
                        $groupKey,
                        $category['label'],
                        $facet['field'],
                        $facet['limit'],
                        $facet['searchable'],
                        $facet['query'],
                        $facet['shape'],
                        $facet['direct'],
                    );
                }

                foreach ($category['items'] ?? [] as $item) {
                    $key = self::facetKey($categoryKey, $item, $facets);
                    $facetKeys[] = $key;
                    $facets[$key] = self::leaf(
                        $item,
                        $groupKey,
                        $category['label'],
                        $category['field'],
                        $category['limit'],
                        true,
                        self::searchableQuery($item),
                        $category['shape'],
                        true,
                    );
                }

                $categories[$categoryKey] = [
                    'label' => $category['label'],
                    'facets' => $facetKeys,
                ];
            }

            $groups[$groupKey] = [
                'label' => $group['label'],
                'categories' => $categories,
            ];
        }

        self::$groupMap = $groups;
        self::$facets = $facets;
    }

    /**
     * @param  array<string, mixed>  $taken
     */
    private static function facetKey(string $categoryKey, string $label, array $taken): string
    {
        $key = self::RESERVED_KEYS[$label] ?? $categoryKey.'_'.Str::slug($label, '_');

        if ($key === $categoryKey.'_') {
            $key .= 'option';
        }

        if (strlen($key) > 80) {
            $key = rtrim(substr($key, 0, 80), '_');
        }

        $base = $key;
        $suffix = 2;

        while (isset($taken[$key])) {
            $key = $base.'_'.$suffix;
            $suffix++;
        }

        return $key;
    }

    private static function searchableQuery(string $label): string
    {
        $query = preg_replace('/[^\pL\pN ._\x27&()-]+/u', ' ', $label) ?? $label;
        $query = trim(preg_replace('/\s+/u', ' ', $query) ?? $query);

        if (mb_strlen($query) > 80) {
            $query = rtrim(mb_substr($query, 0, 80));
            $query = trim(preg_replace('/\s+\S*$/u', '', $query) ?? $query);
        }

        return $query;
    }

    /**
     * @return array{label: string, group: string, parent: string, field: string, limit: string, searchable: bool, query: string, shape: string, direct: bool}
     */
    private static function leaf(
        string $label,
        string $group,
        string $parent,
        string $field,
        string $limit,
        bool $searchable,
        string $query,
        string $shape,
        bool $direct,
    ): array {
        return [
            'label' => $label,
            'group' => $group,
            'parent' => $parent,
            'field' => $field,
            'limit' => $limit,
            'searchable' => $searchable,
            'query' => $query,
            'shape' => $shape,
            'direct' => $direct,
        ];
    }
}
