<?php

namespace App\Campaigns\Platforms;

use App\Campaigns\Targeting\LinkedInAudienceSelections;
use App\Campaigns\Targeting\LinkedInAudienceSize;
use App\Models\Campaign;
use App\Models\PlatformConnection;
use App\Services\LinkedIn\LinkedInTargetingFacets;
use RuntimeException;

/**
 * LinkedIn's rules, as the LinkedIn Campaign Manager API enforces them.
 */
class LinkedInRules implements PlatformRules
{
    public function __construct(private readonly ?LinkedInAudienceSelections $audienceSelections = null) {}

    public function key(): string
    {
        return 'linkedin';
    }

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

    /**
     * @return list<string>
     */
    public function objectives(): array
    {
        return [
            'WEBSITE_VISITS',
            'LEAD_GENERATION',
            'BRAND_AWARENESS',
            'ENGAGEMENT',
            'VIDEO_VIEWS',
            'JOB_APPLY',
            'WEBSITE_CONVERSIONS',
        ];
    }

    public function objectiveFor(string $outcome): ?string
    {
        return match (strtoupper($outcome)) {
            'SALES', 'CONVERSIONS', 'CONVERSION' => 'WEBSITE_CONVERSIONS',
            'LEADS', 'LEAD' => 'LEAD_GENERATION',
            'TRAFFIC', 'VISITS' => 'WEBSITE_VISITS',
            'AWARENESS', 'REACH' => 'BRAND_AWARENESS',
            'ENGAGEMENT' => 'ENGAGEMENT',
            'VIEWS', 'VIDEO' => 'VIDEO_VIEWS',
            'JOB_APPLY', 'JOBS' => 'JOB_APPLY',
            default => null,
        };
    }

    /**
     * @return array{label: string, hint: string}
     */
    public function describeObjective(string $objective): array
    {
        return match ($objective) {
            'WEBSITE_VISITS' => ['label' => 'Website visits', 'hint' => 'Drive traffic to your landing page or website.'],
            'LEAD_GENERATION' => ['label' => 'Lead generation', 'hint' => 'Capture leads using pre-filled LinkedIn forms.'],
            'BRAND_AWARENESS' => ['label' => 'Brand awareness', 'hint' => 'Reach the maximum number of relevant professionals.'],
            'ENGAGEMENT' => ['label' => 'Engagement', 'hint' => 'Increase clicks, social actions, and company page followers.'],
            'VIDEO_VIEWS' => ['label' => 'Video views', 'hint' => 'Maximize views and exposure for your video ads.'],
            'JOB_APPLY' => ['label' => 'Job applicants', 'hint' => 'Drive relevant applicants to your job postings.'],
            'WEBSITE_CONVERSIONS' => ['label' => 'Website conversions', 'hint' => 'Drive valuable actions on your website.'],
            default => ['label' => ucfirst(strtolower(str_replace('_', ' ', $objective))), 'hint' => ''],
        };
    }

    /**
     * @return list<string>
     */
    public function campaignTypes(): array
    {
        return [];
    }

    /**
     * @return array{label: string, hint: string}
     */
    public function describeCampaignType(string $type): array
    {
        return ['label' => $type, 'hint' => ''];
    }

    public function suggestedCampaignType(?Campaign $campaign = null): ?array
    {
        return null;
    }

    /**
     * @return list<string>
     */
    public function bidStrategyFor(string $intent, ?string $objective = null): ?string
    {
        return match (strtoupper($intent)) {
            'AUTOMATIC' => 'AUTOMATED_BID',
            'TARGET_COST' => $this->supportsTargetCost($objective) ? 'TARGET_COST' : null,
            'BID_CAP' => 'MAXIMUM_BID',
            default => null,
        };
    }

    /**
     * Objectives LinkedIn sells no target cost for.
     *
     * Target cost bidding is expressed as an optimizationTargetType of
     * TARGET_COST_PER_CLICK, _PER_IMPRESSION or _PER_VIDEO_VIEW, and LinkedIn
     * allows none of those three on lead generation, website conversions or
     * job applicants: those objectives take only NONE, ENHANCED_CONVERSION and
     * their own maximise target. Offering target cost on them produced a
     * campaign the API rejects at publish, after the campaign group had already
     * been created, so the buyer lost the step rather than the option.
     *
     * @var list<string>
     */
    private const OBJECTIVES_WITHOUT_TARGET_COST = [
        'LEAD_GENERATION',
        'WEBSITE_CONVERSIONS',
        'JOB_APPLY',
    ];

    public function supportsTargetCost(?string $objective): bool
    {
        if (blank($objective)) {
            return true;
        }

        return ! in_array(strtoupper((string) $objective), self::OBJECTIVES_WITHOUT_TARGET_COST, true);
    }

    public function bidStrategies(?string $objective = null, ?string $campaignType = null): array
    {
        $strategies = [
            'AUTOMATED_BID',
            'MAXIMUM_BID',
            'TARGET_COST',
        ];

        if ($this->supportsTargetCost($objective)) {
            return $strategies;
        }

        return array_values(array_diff($strategies, ['TARGET_COST']));
    }

    /**
     * @return list<array{value: string, label: string, hint: string, sends: string}>
     */
    public function bidStrategyOptions(?string $objective = null, ?string $campaignType = null): array
    {
        $options = [
            [
                'value' => 'AUTOMATED_BID',
                'label' => 'Automated bid (Maximum delivery)',
                'hint' => 'Spend the budget for as many results as possible automatically.',
                'sends' => 'Bid automatically for maximum delivery',
            ],
            [
                'value' => 'TARGET_COST',
                'label' => 'Target cost',
                'hint' => 'Hold the average cost per result near a target number you name.',
                'sends' => 'Use target cost bidding',
            ],
            [
                'value' => 'MAXIMUM_BID',
                'label' => 'Maximum bid',
                'hint' => 'Set a cap on the maximum bid for each result or click.',
                'sends' => 'Use maximum bid cap',
            ],
        ];

        $allowed = $this->bidStrategies($objective);

        return array_values(array_filter(
            $options,
            static fn (array $option): bool => in_array($option['value'], $allowed, true),
        ));
    }

    public function bidStrategyNeedsTarget(string $strategy): bool
    {
        return $strategy !== 'AUTOMATED_BID';
    }

    /**
     * @return list<string>
     */
    public function placements(): array
    {
        return [
            'linkedin_feed',
            'linkedin_audience_network',
        ];
    }

    /**
     * @return list<string>
     */
    public function callsToAction(): array
    {
        return [
            'LEARN_MORE',
            'APPLY',
            'DOWNLOAD',
            'SIGN_UP',
            'SUBSCRIBE',
            'REGISTER',
            'JOIN',
            'ATTEND',
            'REQUEST_DEMO',
            'VIEW_QUOTE',
        ];
    }

    /**
     * LinkedIn does not require housing/credit/employment declarations in this format.
     *
     * @return list<string>
     */
    public function specialAdCategories(): array
    {
        return [];
    }

    /**
     * @return list<array{value: string, label: string, hint: string, sends: string, badge?: string|null}>
     */
    public function trackingOptions(): array
    {
        return [
            [
                'value' => 'utm_source=linkedin&utm_medium=paid_social&utm_campaign=arb',
                'label' => 'Standard tagging',
                'hint' => 'Source and medium parameters for LinkedIn.',
                'badge' => 'Suggested',
                'sends' => 'Use the standard UTM tagging',
            ],
        ];
    }

    public function defaultAdAccountId(): ?string
    {
        return PlatformConnection::sharedAccountId('linkedin', config('platforms.linkedin.ad_account_id'));
    }

    /**
     * LinkedIn Campaign Manager enforces a minimum daily budget of $10 USD.
     */
    public function minimumDailyBudget(): float
    {
        return 10.00;
    }

    /**
     * @return list<array{value: string, label: string, hint: string, sends: string}>
     */
    public function budgetModes(): array
    {
        return [
            [
                'value' => 'campaign:daily',
                'label' => 'Daily',
                'hint' => 'Spend this much every day until stopped. LinkedIn requires at least $10/day.',
                'sends' => 'Use a daily campaign budget',
            ],
            ['value' => 'campaign:lifetime', 'label' => 'Lifetime',
                'hint' => 'A total budget spread over a fixed flight; an end date is required.',
                'sends' => 'Use a lifetime campaign budget'],
        ];
    }

    /**
     * Recommended character limits for sponsored content before truncation.
     *
     * @return array<string, int>
     */
    /** One ad per variation, as Meta and LinkedIn both publish them. */
    public function buildsOneAdFromEveryVariation(): bool
    {
        return false;
    }

    public function copyLimits(): array
    {
        return [
            'headline' => 70,
            'description' => 100,
            'primary_text' => 600,
            'introductory_text' => 600,
        ];
    }

    /**
     * @return list<string>
     */
    public function placementsFor(string $objective, ?string $campaignType = null): array
    {
        return $this->placements();
    }

    public function optimizationGoal(string $objective): ?string
    {
        return match ($objective) {
            'WEBSITE_VISITS' => 'CLICKS',
            'LEAD_GENERATION' => 'LEAD_GENERATION',
            'BRAND_AWARENESS' => 'REACH',
            'ENGAGEMENT' => 'ENGAGEMENT',
            'VIDEO_VIEWS' => 'VIDEO_VIEWS',
            'WEBSITE_CONVERSIONS' => 'CONVERSIONS',
            default => 'CLICKS',
        };
    }

    public function conversionEvent(string $objective): ?string
    {
        return match ($objective) {
            'LEAD_GENERATION' => 'LEAD',
            'WEBSITE_VISITS' => 'PAGE_VIEW',
            'WEBSITE_CONVERSIONS' => 'CONVERSION',
            default => null,
        };
    }

    /**
     * No, because nothing in this product can set one for LinkedIn.
     *
     * This returned true for LEAD_GENERATION and WEBSITE_CONVERSIONS, and
     * PublishGate blocks on a blank pixel_id, and steps() has no pixel step,
     * and choose_pixel only speaks to Meta. So a LinkedIn lead-gen campaign was
     * refused at publish for a field no click could ever fill, and the buyer
     * had no way forward at all.
     *
     * A requirement nothing can satisfy is worse than no requirement: it stops
     * the campaign without protecting anything. The same trap is recorded in
     * PublishGate for the campaign name, which blocked on a value nobody was
     * ever asked for.
     *
     * Restoring this means three things together, not one: an Insight Tag
     * chosen through a step, choose_pixel taught to list LinkedIn's conversion
     * rules, and the publisher sending them. Until then a LinkedIn conversion
     * campaign runs without conversion tracking, which is the state every
     * LinkedIn campaign is in today, and it is at least a state the buyer can
     * reach.
     */
    public function requiresPixel(string $objective): bool
    {
        return false;
    }

    public function requiresCreativeAsset(?Campaign $campaign = null): bool
    {
        return true;
    }

    public function uploadsCreativeBeforePublish(): bool
    {
        return true;
    }

    public function requiresPage(): bool
    {
        return true;
    }

    /**
     * @return list<string>
     */
    public function additionalProblems(Campaign $campaign): array
    {
        $problems = $this->professionalTargetingProblems((array) $campaign->audience);

        if ($campaign->ads->map(fn ($ad) => $ad->asset?->kind)->filter()->unique()->count() > 1) {
            $problems[] = 'LinkedIn campaigns cannot mix image and video creative formats.';
        }
        if ($campaign->objective === 'LEAD_GENERATION' && blank($campaign->meta['linkedin_setup']['lead_form']['id'] ?? null)) {
            $problems[] = 'Choose a published LinkedIn Lead Gen Form.';
        }
        if ($campaign->objective === 'WEBSITE_CONVERSIONS' && blank($campaign->meta['linkedin_setup']['conversion']['id'] ?? null)) {
            $problems[] = 'Choose an enabled LinkedIn conversion rule.';
        }
        if ($campaign->objective === 'WEBSITE_CONVERSIONS' && blank($campaign->meta['linkedin_setup']['insight_tag']['id'] ?? null)) {
            $problems[] = 'Verify the LinkedIn Insight Tag on the advertised landing domain.';
        }
        if ($campaign->objective === 'VIDEO_VIEWS' && $campaign->ads->contains(fn ($ad): bool => $ad->asset?->kind !== 'video')) {
            $problems[] = 'Video Views requires a video creative.';
        }
        foreach ($campaign->ads as $ad) {
            if ($ad->asset?->kind === 'video') {
                $reference = $ad->asset->refFor('linkedin', (string) $campaign->ad_account_id)?->external_id;
                if (($campaign->meta['linkedin_video_statuses'][$reference]['status'] ?? null) !== 'AVAILABLE') {
                    $problems[] = 'LinkedIn video is not confirmed AVAILABLE. Refresh asset review before publishing.';
                }
            }
        }

        try {
            ($this->audienceSelections ?? app(LinkedInAudienceSelections::class))->selected($campaign);
        } catch (RuntimeException $exception) {
            $problems[] = 'LinkedIn retargeting segments need review: '.$exception->getMessage();
        }

        if (app(LinkedInAudienceSize::class)->needsConfirmation($campaign)) {
            $problems[] = 'LinkedIn estimates this audience below '.LinkedInTargetingFacets::SMALL_AUDIENCE_MINIMUM.' members, its minimum to deliver. Broaden the audience or confirm publishing with a small audience.';
        }

        $unknown = array_diff((array) ($campaign->placements ?? []), $this->placements());
        if ($unknown !== []) {
            $problems[] = 'placement not supported on LinkedIn: '.implode(', ', $unknown);
        }

        if ($campaign->starts_at && $campaign->ends_at && $campaign->ends_at->lte($campaign->starts_at)) {
            $problems[] = 'end date must be after the start date';
        }

        if (in_array($campaign->objective, ['WEBSITE_VISITS', 'WEBSITE_CONVERSIONS', 'JOB_APPLY'], true) && blank($campaign->landing_url)) {
            $problems[] = 'a destination URL is required for the '.$campaign->objective.' objective on LinkedIn';
        }

        foreach ($campaign->ads as $index => $ad) {
            $label = $campaign->ads->count() > 1 ? 'ad '.($index + 1).': ' : '';
            if (mb_strlen((string) $ad->headline) > 200) {
                $problems[] = "{$label}headline exceeds LinkedIn's 200-character limit";
            }
            if (mb_strlen((string) $ad->primary_text) > 3000) {
                $problems[] = "{$label}primary text exceeds LinkedIn's 3,000-character limit";
            }
        }

        return $problems;
    }

    /** @return list<string> */
    public function professionalTargetingProblems(array $audience): array
    {
        return [...$this->combinationProblems($audience), ...$this->exclusionProblems($audience)];
    }

    /**
     * Included filters LinkedIn will not combine.
     *
     * @return list<string>
     */
    public function combinationProblems(array $audience): array
    {
        $facets = $this->includedFacets($audience);
        $problems = [];
        foreach (LinkedInTargetingFacets::incompatiblePairs() as [$first, $second]) {
            if (! empty($facets[$first]) && ! empty($facets[$second])) {
                $problems[] = 'LinkedIn cannot combine '.LinkedInTargetingFacets::label($first).' with '.LinkedInTargetingFacets::label($second).'. Keep one of these filters.';
            }
        }

        return $problems;
    }

    /**
     * Exclusions LinkedIn rejects: include-only facets, a value both included
     * and excluded, and company size used both ways.
     *
     * @return list<string>
     */
    public function exclusionProblems(array $audience): array
    {
        $included = $this->includedFacets($audience);
        $problems = [];
        foreach ((array) ($audience['linkedin_exclusions'] ?? []) as $facet => $urns) {
            $facet = (string) $facet;
            if (! LinkedInTargetingFacets::excludable($facet)) {
                $problems[] = 'LinkedIn does not allow excluding by '.LinkedInTargetingFacets::label($facet).'. Remove that exclusion.';

                continue;
            }
            if ($urns === [] || empty($included[$facet])) {
                continue;
            }
            if ($facet === 'staffCountRanges') {
                $problems[] = 'LinkedIn allows Company size to be included or excluded, not both. Keep one of these filters.';
            } elseif (array_intersect((array) $urns, (array) $included[$facet]) !== []) {
                $problems[] = 'The same '.LinkedInTargetingFacets::label($facet).' value cannot be both included and excluded. Remove one of them.';
            }
        }

        return $problems;
    }

    /** @return array<string, list<string>> */
    private function includedFacets(array $audience): array
    {
        $facets = (array) ($audience['linkedin_facets'] ?? []);
        if (! empty($audience['seniorities'])) {
            $facets['seniorities'] = [...(array) ($facets['seniorities'] ?? []), ...(array) $audience['seniorities']];
        }

        return $facets;
    }

    /**
     * @return list<array{key: string, label: string, tool: string, offers: bool, ask?: string}>
     */
    public function steps(): array
    {
        return [
            ['key' => 'ad_account', 'label' => 'ad account', 'tool' => 'list_ad_accounts', 'offers' => true,
                'ask' => 'Which LinkedIn ad account should this campaign run on?'],
            ['key' => 'objective', 'label' => 'objective', 'tool' => 'choose_objective', 'offers' => true,
                'ask' => 'What should this campaign optimise for?'],
            ['key' => 'page', 'label' => 'LinkedIn Page', 'tool' => 'choose_page', 'offers' => true,
                'ask' => 'Which LinkedIn Page should publish these ads?'],
            ['key' => 'linkedin_audience', 'label' => 'professional audience', 'tool' => 'choose_linked_in_resource', 'offers' => true,
                'arguments' => ['section' => 'audience']],
            ['key' => 'linkedin_lead_form', 'label' => 'Lead Gen Form', 'tool' => 'choose_linked_in_resource', 'offers' => true,
                'arguments' => ['section' => 'lead_form']],
            ['key' => 'linkedin_conversion', 'label' => 'conversion rule', 'tool' => 'choose_linked_in_resource', 'offers' => true,
                'arguments' => ['section' => 'conversion']],
            ['key' => 'linkedin_insight_tag', 'label' => 'Insight Tag', 'tool' => 'choose_linked_in_resource', 'offers' => false,
                'arguments' => ['section' => 'insight_tag'], 'ask' => 'Verify the account Insight Tag is reporting from the landing domain.'],
            ['key' => 'bidding', 'label' => 'bid strategy', 'tool' => 'set_bidding', 'offers' => true,
                'ask' => 'How should it bid?'],
            ['key' => 'targeting', 'label' => 'countries and placements', 'tool' => 'set_targeting', 'offers' => true,
                'ask' => 'Where should this run, and on which devices?'],
            ['key' => 'location_scope', 'label' => 'location detail', 'tool' => 'choose_location', 'offers' => true,
                'ask' => 'Target whole selected countries, or narrow the US to a specific DMA market?'],
            // No click tracking step, the same as Meta and Google. The value is
            // written at creation from trackingOptions(), so asking cost a
            // question and an answer to arrive at what was going to be used
            // anyway. The buyer is told what was set and can change it.
        ];
    }

    /**
     * @return list<string>
     */
    public function isConfigured(): bool
    {
        // Check database connection first, fall back to config token.
        return filled(PlatformConnection::sharedAccessToken('linkedin', config('platforms.linkedin.token')));
    }

    public function editableAfterPublish(): array
    {
        return ['name', 'budget', 'bid_strategy', 'bid_amount', 'starts_at', 'ends_at'];
    }

    public function supportedAssetRatios(): array
    {
        return ['1.91:1', '1:1', '4:5'];
    }
}
