<?php

namespace App\Campaigns;

/**
 * Fills creative ids, image prompts, and landing-page prompts already implied by a stored review.
 */
class CampaignReviewDetailBackfill
{
    /**
     * @param  array<string, mixed>  $snapshot
     * @return array<string, mixed>|null
     */
    public function apply(array $snapshot): ?array
    {
        $review = $snapshot['review'] ?? null;

        if (! is_array($review)) {
            return null;
        }

        $changed = false;
        $creatives = $review['creatives'] ?? null;

        if (is_array($creatives)) {
            foreach ($creatives as $index => $creative) {
                if (! is_array($creative)) {
                    continue;
                }

                $next = $this->creative($creative, $snapshot, $changed);
                $creatives[$index] = $next;
            }

            $review['creatives'] = $creatives;
        }

        $landing = $review['landing'] ?? null;

        if (is_array($landing) && trim((string) ($landing['prompt'] ?? '')) === '') {
            $prompt = $this->landingPrompt($landing, $snapshot);

            if ($prompt !== '') {
                $landing['prompt'] = $prompt;
                $review['landing'] = $landing;
                $changed = true;
            }
        }

        if (! $changed) {
            return null;
        }

        $snapshot['review'] = $review;

        return $snapshot;
    }

    /**
     * @param  array<string, mixed>  $creative
     * @param  array<string, mixed>  $snapshot
     * @return array<string, mixed>
     */
    private function creative(array $creative, array $snapshot, bool &$changed): array
    {
        if (trim((string) ($creative['creative_id'] ?? '')) === '') {
            $id = $this->creativeId($creative, $snapshot);

            if ($id !== '') {
                $creative['creative_id'] = $id;
                $changed = true;
            }
        }

        $action = strtolower(trim((string) ($creative['action'] ?? '')));
        $prompt = trim((string) ($creative['image_prompt'] ?? ''));

        if ($action === 'change' && $prompt === '' && $this->needsImagePrompt($creative, $snapshot)) {
            $built = $this->imagePrompt($creative, (string) ($snapshot['platform'] ?? 'meta'));

            if ($built !== '') {
                $creative['image_prompt'] = $built;
                $changed = true;
            }
        }

        return $creative;
    }

    /**
     * @param  array<string, mixed>  $creative
     * @param  array<string, mixed>  $snapshot
     */
    private function creativeId(array $creative, array $snapshot): string
    {
        $ad = $this->matchedAd($creative, $snapshot);

        if ($ad === null) {
            return '';
        }

        $id = trim((string) ($ad['creative_id'] ?? ''));

        if ($id !== '') {
            return $id;
        }

        foreach (is_array($ad['images'] ?? null) ? $ad['images'] : [] as $image) {
            if (! is_array($image)) {
                continue;
            }

            $id = trim((string) ($image['creative_id'] ?? ''));

            if ($id !== '') {
                return $id;
            }
        }

        return '';
    }

    /**
     * @param  array<string, mixed>  $creative
     * @param  array<string, mixed>  $snapshot
     */
    private function needsImagePrompt(array $creative, array $snapshot): bool
    {
        $ad = $this->matchedAd($creative, $snapshot);

        if ($ad === null || ! array_key_exists('images', $ad)) {
            return trim((string) ($creative['replacement_headline'] ?? '')) !== ''
                || trim((string) ($creative['replacement_primary_text'] ?? '')) !== '';
        }

        $images = $ad['images'];

        return is_array($images) && $images !== [];
    }

    /**
     * @param  array<string, mixed>  $creative
     * @param  array<string, mixed>  $snapshot
     * @return array<string, mixed>|null
     */
    private function matchedAd(array $creative, array $snapshot): ?array
    {
        $adId = trim((string) ($creative['ad_id'] ?? ''));
        $headline = trim((string) ($creative['current_headline'] ?? ''));

        foreach ($this->catalog($snapshot) as $ad) {
            $candidateId = trim((string) ($ad['ad_id'] ?? ''));
            $candidateHeadline = trim((string) ($ad['headline'] ?? ''));

            if ($adId !== '' && $candidateId === $adId) {
                return $ad;
            }

            if ($headline !== '' && $candidateHeadline === $headline) {
                return $ad;
            }
        }

        return null;
    }

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

        foreach (['ads', 'creatives'] as $key) {
            $rows = data_get($snapshot, 'creative_context.'.$key, []);

            if (! is_array($rows)) {
                continue;
            }

            foreach ($rows as $ad) {
                if (is_array($ad)) {
                    $catalog[] = $ad;
                }
            }
        }

        return $catalog;
    }

    /**
     * @param  array<string, mixed>  $creative
     */
    private function imagePrompt(array $creative, string $platform = 'meta'): string
    {
        $headline = trim((string) ($creative['replacement_headline'] ?? ''));
        $primary = $this->withoutDigits((string) ($creative['replacement_primary_text'] ?? ''));
        $why = $this->withoutDigitSentences((string) ($creative['why'] ?? ''));

        if ($headline === '' && $primary === '') {
            return '';
        }

        $platformName = match (strtolower(trim($platform))) {
            'linkedin' => 'LinkedIn',
            'google' => 'Google',
            default => 'Meta',
        };
        $ratio = match ($platformName) {
            'LinkedIn' => '1:1',
            'Google' => '1.91:1',
            default => '4:5',
        };

        $parts = [
            $ratio.' '.$platformName.' feed still, portrait crop, one frame. The studio makes the still. This app does not generate it.',
        ];

        if ($headline !== '') {
            $parts[] = 'Exact on-image line: "'.$headline.'". High-contrast type, no extra slogans, no button chrome on the image.';
        }

        if ($primary !== '') {
            $parts[] = 'Scene and offer: '.$primary.'. Show one clear subject in a real setting with directional light. Do not invent a logo or a price.';
        }

        if ($why !== '') {
            $parts[] = 'Change from the current still: '.$why;
        }

        $parts[] = 'Leave out other-product marks, crowded UI, and any claim that is not in the replacement copy.';

        return implode(' ', $parts);
    }

    /**
     * @param  array<string, mixed>  $landing
     * @param  array<string, mixed>  $snapshot
     */
    private function landingPrompt(array $landing, array $snapshot): string
    {
        $headline = trim((string) ($landing['headline'] ?? ''));
        $section = $this->withoutDigits((string) ($landing['section'] ?? $landing['content'] ?? ''));
        $cta = trim((string) ($landing['cta'] ?? ''));
        $flow = $this->withoutDigits((string) ($landing['flow'] ?? ''));

        if ($headline === '' && $section === '' && $cta === '') {
            return '';
        }

        $type = $this->pageType($snapshot);
        $prompt = 'This is '.$type.'. '.$this->pageContrast($type);

        if ($headline !== '') {
            $prompt .= ' First screen: the headline '.$headline;
            $prompt .= $cta !== '' ? ' and one button, '.$cta.'.' : '.';
        } elseif ($cta !== '') {
            $prompt .= ' The button reads '.$cta.'.';
        }

        if ($section !== '') {
            $prompt .= ' Next: '.$section;
        }

        if ($flow !== '' && $flow !== $section) {
            $prompt .= ' Page order: '.$flow;
        }

        return trim($prompt);
    }

    /**
     * @param  array<string, mixed>  $snapshot
     */
    private function pageType(array $snapshot): string
    {
        $objective = strtoupper(trim((string) data_get(
            $snapshot,
            'campaign_goals.objective',
            data_get($snapshot, 'campaign_profile.objective', ''),
        )));
        $goals = [];

        foreach (data_get($snapshot, 'campaign_goals.optimization_goals', []) as $goal) {
            if (is_string($goal) && trim($goal) !== '') {
                $goals[] = strtoupper(trim($goal));
            }
        }

        $single = trim((string) data_get($snapshot, 'campaign_goals.optimization_goal', ''));

        if ($single !== '') {
            $goals[] = strtoupper($single);
        }

        if (array_intersect($goals, ['LEAD_GENERATION', 'QUALITY_LEAD', 'QUALITY_CALL', 'CONVERSATIONS']) !== []) {
            return 'an instant lead form';
        }

        if (str_contains($objective, 'APP') || array_intersect($goals, ['APP_INSTALLS', 'APP_INSTALL']) !== []) {
            return 'a download page';
        }

        if (str_contains($objective, 'LEAD')) {
            return 'an offsite sign-up page';
        }

        if (str_contains($objective, 'SALE') || str_contains($objective, 'PURCHASE')) {
            return 'a purchase page';
        }

        if (str_contains($objective, 'TRAFFIC') || in_array('LINK_CLICKS', $goals, true)) {
            return 'a visit page';
        }

        if ($objective !== '') {
            $label = strtolower(str_replace(['OUTCOME_', '_'], ['', ' '], $objective));

            return 'a '.trim($label).' page';
        }

        return 'a landing page';
    }

    private function pageContrast(string $type): string
    {
        return match ($type) {
            'an offsite sign-up page' => 'Not a Meta instant lead form and not an app download.',
            'an instant lead form' => 'Not a website sign-up page and not an app download.',
            'a download page' => 'Not a lead form and not a purchase page.',
            'a purchase page' => 'Not a lead form and not an app download.',
            'a visit page' => 'Not a lead form and not an app download.',
            default => 'Matched to the campaign objective.',
        };
    }

    private function withoutDigits(string $text): string
    {
        $text = trim(preg_replace('/\s+/', ' ', $text) ?? '');

        if ($text === '' || preg_match('/\d/', $text) !== 1) {
            return $text;
        }

        return '';
    }

    private function withoutDigitSentences(string $text): string
    {
        $text = trim(preg_replace('/\s+/', ' ', $text) ?? '');
        $sentences = preg_split('/(?<=\.)\s+/', $text) ?: [];
        $kept = [];

        foreach ($sentences as $sentence) {
            $sentence = trim($sentence);

            if ($sentence === '' || preg_match('/\d/', $sentence) === 1) {
                continue;
            }

            $kept[] = $sentence;
        }

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