<?php

namespace App\Campaigns;

use App\Services\Meta\MetaTargetingBrowse;

/**
 * Audience advice using Ads Manager browse rows Meta can actually target.
 * Job titles stay a Work search box. Brand names are not interests.
 */
class AdSetAudienceAction
{
    /**
     * @var list<array{
     *     needles: list<string>,
     *     who: string,
     *     interests: list<string>,
     *     industries: list<string>,
     *     behaviors: list<string>,
     *     job_titles: list<string>
     * }>
     */
    private const DOMAINS = [
        [
            'needles' => ['lucos', 'cursor', 'copilot', 'github', 'vscode', 'vs code', 'developer', 'developers', 'coding', 'software engineer'],
            'who' => 'developers',
            'interests' => [
                'Software (computers & electronics)',
                'Web development (websites)',
                'Engineering (science)',
            ],
            'industries' => [
                'IT and technical services',
                'Computation and mathematics',
                'IT decision makers',
            ],
            'behaviors' => [
                'Early technology adopters',
            ],
            'job_titles' => [
                'Software engineer',
            ],
        ],
        [
            'needles' => ['searchbrowser', 'search_browser', 'search browser'],
            'who' => 'Mac users looking for a desktop browser',
            'interests' => [
                'Software (computers & electronics)',
                'Desktop computers (consumer electronics)',
                'Web development (websites)',
            ],
            'industries' => [
                'IT and technical services',
            ],
            'behaviors' => [
                'Facebook access (OS): Mac OS X',
                'Early technology adopters',
            ],
            'job_titles' => [],
        ],
        [
            'needles' => ['chatgpt', 'openai', 'search.com', 'search_newflow', 'ai search', 'perplexity', 'grok', 'claude'],
            'who' => 'people who search and work in software',
            'interests' => [
                'Software (computers & electronics)',
                'Web development (websites)',
                'Engineering (science)',
                'Search engine optimization (software)',
            ],
            'industries' => [
                'IT and technical services',
                'IT decision makers',
                'Computation and mathematics',
            ],
            'behaviors' => [
                'Early technology adopters',
            ],
            'job_titles' => [
                'Software engineer',
            ],
        ],
        [
            'needles' => ['attestpath', 'soc 2', 'soc2', 'compliance', 'iso 27001', 'security audit'],
            'who' => 'business and IT decision makers',
            'interests' => [
                'Small business (business & finance)',
                'Entrepreneurship (business & finance)',
            ],
            'industries' => [
                'Business decision makers',
                'IT decision makers',
            ],
            'behaviors' => [
                'Small business owners',
            ],
            'job_titles' => [
                'Software engineer',
            ],
        ],
        [
            'needles' => ['mortgage', 'loan', 'credit card', 'insurance', 'banking', 'fintech'],
            'who' => 'people comparing financial products',
            'interests' => [
                'Mortgage loans (banking)',
                'Credit cards (credit & lending)',
                'Insurance (business & finance)',
                'Online banking (banking)',
            ],
            'industries' => [
                'Business and finance',
            ],
            'behaviors' => [
                'Engaged shoppers',
            ],
            'job_titles' => [],
        ],
        [
            'needles' => ['dental', 'clinic', 'therapy', 'wellness', 'patient', 'healthcare'],
            'who' => 'people looking for that kind of care',
            'interests' => [],
            'industries' => [
                'Healthcare and medical services',
            ],
            'behaviors' => [
                'Health and wellness creators',
            ],
            'job_titles' => [],
        ],
        [
            'needles' => ['bootcamp', 'online course', 'university', 'certification course'],
            'who' => 'learners and career switchers',
            'interests' => [
                'Higher education (education)',
            ],
            'industries' => [
                'Education and libraries',
            ],
            'behaviors' => [],
            'job_titles' => [],
        ],
        [
            'needles' => ['realtor', 'real estate', 'apartment', 'home buyer'],
            'who' => 'people actively looking for a home',
            'interests' => [
                'Real estate (industry)',
            ],
            'industries' => [],
            'behaviors' => [],
            'life_events' => [
                'Recently moved',
            ],
            'job_titles' => [],
        ],
        [
            'needles' => ['flight', 'hotel', 'vacation', 'travel deal'],
            'who' => 'travelers planning a trip',
            'interests' => [],
            'industries' => [],
            'behaviors' => [
                'Frequent travellers',
                'Frequent international travellers',
            ],
            'job_titles' => [],
        ],
        [
            'needles' => ['skincare', 'makeup', 'cosmetic', 'beauty'],
            'who' => 'people shopping that kind of beauty product',
            'interests' => [],
            'industries' => [],
            'behaviors' => [
                'Health and beauty Page admins',
                'Engaged shoppers',
            ],
            'job_titles' => [],
        ],
        [
            'needles' => ['workout', 'fitness', 'gym', 'personal trainer'],
            'who' => 'people training or looking for a program',
            'interests' => [],
            'industries' => [],
            'behaviors' => [
                'Health and wellness creators',
            ],
            'job_titles' => [],
        ],
        [
            'needles' => ['restaurant', 'recipe', 'food delivery'],
            'who' => 'people choosing what to eat',
            'interests' => [
                'Food and restaurants',
            ],
            'industries' => [
                'Food and restaurants',
            ],
            'behaviors' => [
                'Food and drink creators',
            ],
            'job_titles' => [],
        ],
        [
            'needles' => ['video game', 'gamer', 'steam', 'gaming'],
            'who' => 'players of that kind of game',
            'interests' => [
                'Video games (gaming)',
                'Online games (video games)',
            ],
            'industries' => [],
            'behaviors' => [
                'Console gamers',
            ],
            'job_titles' => [],
        ],
    ];

    /**
     * @param  array<string, mixed>  $row
     */
    public static function contextFromRow(array $row): string
    {
        $parts = [
            (string) ($row['name'] ?? ''),
            (string) data_get($row, 'creative_context.landing_url'),
            (string) data_get($row, 'review.landing.headline'),
            (string) data_get($row, 'review.landing.section'),
            (string) data_get($row, 'review.landing.problem'),
        ];

        foreach (is_array(data_get($row, 'review.creatives')) ? data_get($row, 'review.creatives') : [] as $creative) {
            if (! is_array($creative)) {
                continue;
            }

            foreach (['current_headline', 'replacement_headline', 'replacement_primary_text'] as $key) {
                $parts[] = (string) ($creative[$key] ?? '');
            }
        }

        return trim(implode(' ', array_filter($parts, fn (string $part): bool => trim($part) !== '')));
    }

    public static function who(string $context): ?string
    {
        return self::match(mb_strtolower($context))['who'] ?? null;
    }

    public static function suggest(string $context, string $audienceType = '', string $platform = 'meta'): ?string
    {
        $type = strtolower(trim($audienceType));
        $plat = strtolower(trim($platform));
        $domain = self::match(mb_strtolower($context));

        if (in_array($type, ['retargeting', 'custom'], true)) {
            $text = match ($plat) {
                'linkedin' => 'Keep this Matched Audience retargeting list. Widen it with longer visitor windows, company page engagers, or video viewers, and exclude members who already converted.',
                'google' => 'Keep this remarketing list. Widen it with longer visitor windows or YouTube viewers, and exclude people who already converted.',
                default => 'Keep this retargeting list. Widen it with longer visitor windows, page and Instagram engagers, or video viewers, and exclude people who already converted. Do not add cold interests to this ad set.',
            };

            if ($domain !== null) {
                $text .= ' For a separate prospecting ad set: '.$domain['targeting'];
            }

            return $text;
        }

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

        if ($type === 'lookalike') {
            if ($plat === 'linkedin') {
                return 'Keep this Lookalike Audience. If reach is too small, expand the audience size slider from the seed list.';
            }

            return 'Keep this lookalike. If reach is too small, build a broader lookalike from the same seed instead of stacking cold interests.';
        }

        if ($type === 'broad' || $type === 'interest' || $type === '') {
            $around = self::interestPhrase($domain);

            if ($plat === 'linkedin') {
                return 'A '.$domain['who'].' angle can use LinkedIn job functions, member skills, or company industries around '.$around.'. Use LinkedIn Audience Network when delivery is thin.';
            }

            if ($plat === 'google') {
                return 'A '.$domain['who'].' angle can use Google custom segments and keywords around '.$around.'.';
            }

            return 'Broad targeting lets Meta pick the audience. That is not a detailed-targeting plan. '.$domain['targeting'];
        }

        return 'Keep the '.($type !== '' ? $type.' ' : '').'audience unless reach is too small to deliver.';
    }

    /**
     * @return array{who: string, targeting: string, interests: list<string>}|null
     */
    private static function match(string $haystack): ?array
    {
        if ($haystack === '') {
            return null;
        }

        foreach (self::DOMAINS as $domain) {
            foreach ($domain['needles'] as $needle) {
                if (str_contains($haystack, $needle)) {
                    return [
                        'who' => $domain['who'],
                        'interests' => $domain['interests'],
                        'targeting' => self::targetingLine($domain),
                    ];
                }
            }
        }

        return null;
    }

    /**
     * @param  array{who: string, targeting: string, interests: list<string>}  $domain
     */
    private static function interestPhrase(array $domain): string
    {
        $names = array_values(array_filter(
            $domain['interests'],
            fn (mixed $name): bool => is_string($name) && trim($name) !== '',
        ));

        if ($names === []) {
            return $domain['who'];
        }

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

    /**
     * @param  array<string, mixed>  $domain
     */
    private static function targetingLine(array $domain): string
    {
        $parts = [];

        foreach ([
            'Interests' => $domain['interests'] ?? [],
            'Demographics → Industries' => $domain['industries'] ?? [],
            'Demographics → Life events' => $domain['life_events'] ?? [],
            'Behaviors' => $domain['behaviors'] ?? [],
        ] as $path => $names) {
            $valid = self::browseNames($names);

            if ($valid !== []) {
                $parts[] = $path.': '.implode(', ', $valid);
            }
        }

        $jobs = array_values(array_filter(
            is_array($domain['job_titles'] ?? null) ? $domain['job_titles'] : [],
            fn (mixed $name): bool => is_string($name) && trim($name) !== '',
        ));

        if ($jobs !== []) {
            $parts[] = 'Demographics → Work → Job titles (search box): '.implode(', ', $jobs);
        }

        if ($parts === []) {
            return 'Use Ads Manager Detailed targeting from the browse menu, not a brand name.';
        }

        return 'In Ads Manager open Detailed targeting and pick these browse rows Meta has on file. '.implode('. ', $parts).'. Do not type a brand or website as an interest or placement.';
    }

    /**
     * @param  list<mixed>  $names
     * @return list<string>
     */
    private static function browseNames(array $names): array
    {
        $allowed = MetaTargetingBrowse::namedItems();
        $out = [];

        foreach ($names as $name) {
            if (! is_string($name) || $name === '' || ! in_array($name, $allowed, true)) {
                continue;
            }

            $out[] = $name;
        }

        return $out;
    }
}
