<?php

namespace App\Campaigns\Manager;

use App\Campaigns\Manager\Editing\EditCapabilities;
use App\Models\CampaignPlatformEntity;
use App\Models\CampaignSyncRun;
use Carbon\CarbonImmutable;
use Illuminate\Support\Str;
use Throwable;

/**
 * Words and values for the campaign manager screens.
 *
 * Entity types keep each platform's vocabulary: a Google ad group is never
 * called an ad set, and a LinkedIn sponsored creative is not called an ad.
 */
final class ManagerFormat
{
    private const array TYPES = [
        'campaign' => 'Campaign',
        'campaign_group' => 'Campaign group',
        'ad_set' => 'Ad set',
        'ad_group' => 'Ad group',
        'asset_group' => 'Asset group',
        'ad' => 'Ad',
        'creative' => 'Sponsored creative',
    ];

    private const array PLATFORMS = [
        'meta' => 'Meta',
        'google' => 'Google Ads',
        'linkedin' => 'LinkedIn',
    ];

    /** Fields whose own names read poorly as labels. */
    private const array FIELD_LABELS = [
        'age_min' => 'Youngest age',
        'age_max' => 'Oldest age',
        'genders' => 'Gender',
        'publisher_platforms' => 'Placements',
        'geo_locations' => 'Included locations (advanced)',
        'excluded_geo_locations' => 'Excluded locations',
        'flexible_spec' => 'Detailed audience (AND / OR groups)',
        'locales' => 'Audience languages',
        'advantage_audience' => 'Advantage+ audience',
        'roas_floor' => 'Minimum ROAS',
        'adset_schedule' => 'Delivery windows (dayparting)',
        'delivery_schedule' => 'Delivery windows (account time zone)',
        'targeting_criteria' => 'Audience targeting',
        'audience_expansion' => 'Audience expansion',
        'conversion_event' => 'Website conversion event',
        'conversion_rules' => 'LinkedIn conversion rules',
        'offsite_delivery' => 'LinkedIn Audience Network',
        'frequency_optimization' => 'LinkedIn frequency optimization',
        'conversion_goals' => 'Google conversion goals',
        'network_settings' => 'Google delivery networks',
        'geo_target_type' => 'Geographic presence / interest',
        'pacing_type' => 'Delivery pacing',
        'budget_schedules' => 'Scheduled budget boosts',
        'user_os' => 'Operating systems and versions',
        'user_device' => 'Included devices',
        'excluded_user_device' => 'Excluded devices',
        'wireless_carrier' => 'Connections (Wi-Fi / carriers)',
        'targeting_relaxation_types' => 'Audience expansion rules',
        'audience_criteria' => 'Demographics and audiences',
    ];

    /**
     * Money shown at the top of an object, by field, in the order it is shown.
     *
     * @var array<string, array{string, string}>
     */
    private const array MONEY_FACTS = [
        'daily_budget' => ['Daily budget', 'bi-wallet2'],
        'lifetime_budget' => ['Lifetime budget', 'bi-wallet2'],
        'total_budget' => ['Total budget', 'bi-wallet2'],
        'bid_amount' => ['Bid', 'bi-hammer'],
        'cpc_bid' => ['Max CPC', 'bi-hammer'],
        'unit_cost' => ['Bid', 'bi-hammer'],
    ];

    /** @var array<string, array{string, string}> */
    private const array WORD_FACTS = [
        'objective' => ['Objective', 'bi-flag'],
        'objectiveType' => ['Objective', 'bi-flag'],
        'channel_type' => ['Channel', 'bi-broadcast'],
        'bid_strategy' => ['Bid strategy', 'bi-sliders'],
        'costType' => ['Cost type', 'bi-sliders'],
        'optimization_goal' => ['Optimising for', 'bi-crosshair'],
        'optimizationTargetType' => ['Optimising for', 'bi-crosshair'],
        'headline' => ['Headline', 'bi-type'],
    ];

    /** Kept upper-case when an enum is put into words. */
    private const array ACRONYMS = ['CPC', 'CPM', 'CPA', 'CPV', 'ROAS', 'URL', 'CTR', 'TV', 'ID'];

    public static function type(?string $type): string
    {
        return self::TYPES[(string) $type] ?? Str::headline((string) $type);
    }

    public static function platform(?string $platform): string
    {
        return self::PLATFORMS[(string) $platform] ?? Str::headline((string) $platform);
    }

    public static function field(?string $field): string
    {
        if ($field === null || $field === '') {
            return '';
        }

        if (isset(self::FIELD_LABELS[$field])) {
            return self::FIELD_LABELS[$field];
        }

        return (string) preg_replace_callback(
            '/\b('.implode('|', self::ACRONYMS).')\b/i',
            fn (array $match): string => strtoupper($match[1]),
            Str::headline(Str::after($field, 'settings.')),
        );
    }

    public static function value(mixed $value): string
    {
        return match (true) {
            $value === null, $value === '', $value === [] => '—',
            is_bool($value) => $value ? 'Yes' : 'No',
            is_array($value) => (string) json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
            default => (string) $value,
        };
    }

    /**
     * A value as a person would write it: enum constants in words, timestamps
     * as dates, short lists joined. Anything structured falls back to JSON.
     */
    public static function readable(mixed $value): string
    {
        return match (true) {
            is_string($value) && self::isEnum($value) => self::words($value),
            is_string($value) && ($moment = self::moment($value)) !== null => $moment,
            self::isShortList($value) => implode(', ', array_map(self::readable(...), $value)),
            default => self::value($value),
        };
    }

    /**
     * One stored setting, with money in the object's currency.
     *
     * LinkedIn keeps money as {amount, currencyCode} and its run schedule as
     * epoch milliseconds, so both are recognised by shape.
     */
    public static function setting(string $field, mixed $value, CampaignPlatformEntity $entity): string
    {
        if (EditCapabilities::isMoney($field) && is_numeric($value)) {
            return self::money((float) $value, EditCapabilities::currency($entity));
        }

        if (is_array($value) && self::isMoneyShape($value) && is_numeric($value['amount'])) {
            return self::money((float) $value['amount'], strtoupper((string) $value['currencyCode']));
        }

        if (is_array($value) && self::isScheduleShape($value)) {
            return self::schedule($value['start'], $value['end'] ?? null);
        }

        if (is_string($value) && $value !== '' && ($field === 'bid_strategy' || ($entity->platform === 'linkedin' && $field === 'optimizationTargetType'))) {
            return EditCapabilities::strategyLabel($entity->platform, $value);
        }

        if (is_string($value) && $value !== '' && $entity->platform === 'meta' && $field === 'optimization_goal') {
            return EditCapabilities::goalLabel($value);
        }

        return self::readable($value);
    }

    public static function isLong(mixed $value): bool
    {
        if (self::isShortList($value)) {
            return false;
        }

        return is_array($value) && $value !== [] && ! self::isMoneyShape($value) && ! self::isScheduleShape($value)
            || is_string($value) && mb_strlen($value) > 80;
    }

    /**
     * The handful of settings worth seeing without opening anything: budget,
     * bid, goal and run dates, in the platform's own words.
     *
     * @return list<array{label: string, value: string, icon: string}>
     */
    public static function highlights(CampaignPlatformEntity $entity): array
    {
        $settings = (array) $entity->settings;
        $currency = EditCapabilities::currency($entity);
        $facts = [];

        foreach (self::MONEY_FACTS as $field => [$label, $icon]) {
            $amount = EditCapabilities::current($entity, $field);

            if (is_float($amount) && $amount > 0) {
                $facts[] = ['label' => $label, 'value' => self::money($amount, $currency), 'icon' => $icon];
            }
        }

        foreach (self::WORD_FACTS as $field => [$label, $icon]) {
            $value = $settings[$field] ?? null;

            if (is_string($value) && $value !== '') {
                $value = match (true) {
                    $field === 'bid_strategy' => EditCapabilities::strategyLabel($entity->platform, $value),
                    $field === 'optimization_goal' && $entity->platform === 'meta' => EditCapabilities::goalLabel($value),
                    self::isEnum($value) => self::words($value),
                    default => Str::limit($value, 60),
                };
                $facts[] = ['label' => $label, 'value' => $value, 'icon' => $icon];
            }
        }

        [$start, $end] = match (true) {
            isset($settings['runSchedule']) && is_array($settings['runSchedule']) => [$settings['runSchedule']['start'] ?? null, $settings['runSchedule']['end'] ?? null],
            default => [$settings['start_time'] ?? $settings['start_date'] ?? null, $settings['stop_time'] ?? $settings['end_time'] ?? $settings['end_date'] ?? null],
        };

        if (filled($start) || filled($end)) {
            $facts[] = ['label' => 'Runs', 'value' => self::schedule($start, $end), 'icon' => 'bi-calendar3'];
        }

        return $facts;
    }

    /**
     * A platform status as a coloured pill.
     *
     * @return array{label: string, class: string}
     */
    public static function status(?string $status): array
    {
        $key = strtoupper((string) $status);

        $class = match (true) {
            in_array($key, ['ACTIVE', 'ENABLED', 'APPROVED', 'ELIGIBLE', 'SERVING', 'RUNNABLE', 'APPROVED_LIMITED'], true) => 'completed',
            in_array($key, ['DELETED', 'REMOVED', 'DISAPPROVED', 'WITH_ISSUES', 'CANCELED', 'CANCELLED', 'NOT_ELIGIBLE', 'REJECTED'], true) => 'failed',
            str_contains($key, 'PENDING') || str_contains($key, 'REVIEW') || str_contains($key, 'LIMITED') || str_contains($key, 'LEARNING') || $key === 'IN_PROCESS' => 'generating',
            default => 'queued',
        };

        return ['label' => $key === '' ? '—' : self::words($key), 'class' => $class];
    }

    public static function platformIcon(?string $platform): string
    {
        return match ((string) $platform) {
            'meta' => 'bi-meta',
            'google' => 'bi-google',
            'linkedin' => 'bi-linkedin',
            default => 'bi-broadcast',
        };
    }

    public static function typeIcon(?string $type): string
    {
        return match ((string) $type) {
            'campaign' => 'bi-megaphone',
            'campaign_group' => 'bi-collection',
            'ad_set', 'ad_group' => 'bi-bullseye',
            'asset_group' => 'bi-grid-3x3-gap',
            'ad', 'creative' => 'bi-image',
            default => 'bi-dot',
        };
    }

    private static function money(float $amount, string $currency): string
    {
        return EditCapabilities::money($amount, $currency).' '.$currency;
    }

    private static function schedule(mixed $start, mixed $end): string
    {
        $from = self::moment($start) ?? (filled($start) ? (string) $start : 'Not set');
        $to = self::moment($end) ?? (filled($end) ? (string) $end : 'no end date');

        return $from.' → '.$to;
    }

    /** A timestamp the platform sent, formatted; null when it is not one. */
    private static function moment(mixed $value): ?string
    {
        try {
            return match (true) {
                is_int($value) && $value > 100_000_000_000, is_string($value) && preg_match('/^\d{12,13}$/', $value) === 1 => CarbonImmutable::createFromTimestampMs((int) $value, config('app.timezone'))->format('M j, Y'),
                is_string($value) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) === 1 => CarbonImmutable::parse($value)->format('M j, Y'),
                is_string($value) && preg_match('/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/', $value) === 1 => CarbonImmutable::parse($value)->format('M j, Y g:i A'),
                default => null,
            };
        } catch (Throwable) {
            return null;
        }
    }

    /** OUTCOME_LEADS, LOWEST_COST_WITHOUT_CAP, AUCTION - but not USD or CPM. */
    private static function isEnum(string $value): bool
    {
        return preg_match('/^[A-Z][A-Z0-9]*(_[A-Z0-9]+)+$/', $value) === 1
            || preg_match('/^[A-Z]{5,}$/', $value) === 1;
    }

    private static function words(string $value): string
    {
        $words = array_map(
            fn (string $word): string => in_array($word, self::ACRONYMS, true) ? $word : strtolower($word),
            explode('_', $value),
        );

        return ucfirst(implode(' ', $words));
    }

    private static function isShortList(mixed $value): bool
    {
        return is_array($value) && $value !== [] && array_is_list($value) && count($value) <= 8
            && array_filter($value, fn (mixed $item): bool => ! is_scalar($item) || is_string($item) && mb_strlen($item) > 40) === [];
    }

    /** @param  array<mixed>  $value */
    private static function isMoneyShape(array $value): bool
    {
        return isset($value['amount'], $value['currencyCode']) && count($value) === 2;
    }

    /** @param  array<mixed>  $value */
    private static function isScheduleShape(array $value): bool
    {
        return array_key_exists('start', $value) && count(array_diff_key($value, ['start' => 0, 'end' => 0])) === 0;
    }

    /**
     * How fresh the stored picture is, for a badge.
     *
     * @return array{label: string, class: string}
     */
    public static function freshness(?CampaignSyncRun $latest, ?CampaignSyncRun $lastGood, int $staleAfterMinutes): array
    {
        return match (true) {
            $latest === null => ['label' => 'Never read', 'class' => 'queued'],
            $latest->status === CampaignSyncRun::Running => ['label' => 'Reading', 'class' => 'generating'],
            $latest->status === CampaignSyncRun::Failed => ['label' => $lastGood === null ? 'Read failed' : 'Last read failed', 'class' => 'failed'],
            $lastGood !== null && $lastGood->started_at->lt(now()->subMinutes($staleAfterMinutes)) => ['label' => 'Stale', 'class' => 'generating'],
            $latest->status === CampaignSyncRun::Partial => ['label' => 'Partly read', 'class' => 'generating'],
            default => ['label' => 'Up to date', 'class' => 'completed'],
        };
    }
}
