<?php

namespace App\Library\CampaignDecision;

/**
 * Turns a verdict into a budget change with a percent and, when the daily budget is known, dollar amounts.
 */
class CampaignBudgetRecommendation
{
    /**
     * @param  array<string, mixed>|null  $snapshot
     * @return array{
     *     current_daily_budget: ?float,
     *     change_percent: int,
     *     change_amount: ?float,
     *     recommended_daily_budget: ?float,
     *     summary: string
     * }|null
     */
    public static function fromStored(?string $status, ?array $snapshot = null, ?float $dailyBudget = null, ?int $changePercent = null): ?array
    {
        $verdict = CampaignDecisionVerdict::tryFromStored($status);

        if ($verdict === null && is_array($snapshot)) {
            $storedVerdict = $snapshot['verdict'] ?? null;
            $verdict = CampaignDecisionVerdict::tryFromStored(is_string($storedVerdict) ? $storedVerdict : null);
        }

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

        if (is_array($snapshot) && is_numeric($snapshot['recommended_budget_change_percent'] ?? null)) {
            $percent = (int) $snapshot['recommended_budget_change_percent'];
        } elseif ($changePercent !== null) {
            $percent = $changePercent;
        } else {
            $percent = self::configuredPercent($verdict);
        }

        $current = self::budgetOrNull($dailyBudget)
            ?? self::budgetOrNull(is_array($snapshot) ? ($snapshot['daily_budget'] ?? null) : null)
            ?? self::budgetOrNull(is_array($snapshot) ? data_get($snapshot, 'campaign_profile.daily_budget') : null);

        return self::describe($verdict, $percent, $current);
    }

    /**
     * @return array{
     *     current_daily_budget: ?float,
     *     change_percent: int,
     *     change_amount: ?float,
     *     recommended_daily_budget: ?float,
     *     summary: string
     * }
     */
    public static function describe(CampaignDecisionVerdict $verdict, int $changePercent, ?float $dailyBudget): array
    {
        $current = self::budgetOrNull($dailyBudget);
        $recommended = null;
        $changeAmount = null;

        if ($current !== null && $changePercent !== 0) {
            $recommended = round($current * (1 + ($changePercent / 100)), 2);
            $changeAmount = round($recommended - $current, 2);
        }

        return [
            'current_daily_budget' => $current,
            'change_percent' => $changePercent,
            'change_amount' => $changeAmount,
            'recommended_daily_budget' => $recommended,
            'summary' => self::summary($verdict, $changePercent, $current, $recommended, $changeAmount),
        ];
    }

    public static function applyToText(string $text, ?string $summary): string
    {
        $summary = trim((string) $summary);

        if ($summary === '' || stripos($text, 'daily budget') !== false) {
            return $text;
        }

        $lead = rtrim($summary, '.');

        foreach (self::openingLabels() as $label) {
            $pattern = '/^'.preg_quote($label, '/').'\s*:/i';

            if (preg_match($pattern, $text) === 1) {
                return preg_replace_callback(
                    $pattern,
                    static fn (): string => $lead.':',
                    $text,
                    1,
                ) ?? $text;
            }
        }

        return $lead.'. '.$text;
    }

    /**
     * @param  list<mixed>  $lines
     * @return list<string>
     */
    public static function mergeIntoPlan(array $lines, ?string $summary): array
    {
        $summary = trim((string) $summary);
        $strings = array_values(array_filter($lines, is_string(...)));

        if ($summary === '' || self::linesMentionBudget($strings)) {
            return $strings;
        }

        $pattern = '/^(?:Decrease budget stays|Pause stays|Scale up stays|Spend more|Keep watching until there is enough click and conversion evidence|Keep watching)\.\s*/';
        $replaced = false;
        $merged = [];

        foreach ($strings as $line) {
            if (! $replaced && preg_match($pattern, $line) === 1) {
                $rest = trim((string) preg_replace($pattern, '', $line, 1));
                $line = $rest === '' ? $summary : rtrim($summary, '.').'. '.$rest;
                $replaced = true;
            }

            $merged[] = $line;
        }

        if (! $replaced && isset($merged[1])) {
            $merged[1] = rtrim($summary, '.').'. '.$merged[1];
        } elseif (! $replaced) {
            $merged[] = $summary;
        }

        return $merged;
    }

    /**
     * @param  list<string>  $lines
     */
    private static function linesMentionBudget(array $lines): bool
    {
        foreach ($lines as $line) {
            if (stripos($line, 'daily budget') !== false) {
                return true;
            }
        }

        return false;
    }

    private static function summary(
        CampaignDecisionVerdict $verdict,
        int $changePercent,
        ?float $current,
        ?float $recommended,
        ?float $changeAmount,
    ): string {
        return match ($verdict) {
            CampaignDecisionVerdict::ScaleUp => self::changeSentence('Increase', 'more', $changePercent, $current, $recommended, $changeAmount),
            CampaignDecisionVerdict::DecreaseBudget => self::changeSentence('Decrease', 'less', $changePercent, $current, $recommended, $changeAmount),
            CampaignDecisionVerdict::Pause => $current !== null
                ? 'Pause the campaign and stop all of the '.self::dollars($current).' daily budget.'
                : 'Pause the campaign and stop all spend.',
            CampaignDecisionVerdict::Maintain => $current !== null
                ? 'Keep the daily budget at '.self::dollars($current).'.'
                : 'Keep the daily budget unchanged.',
            CampaignDecisionVerdict::Learning => $current !== null
                ? 'Leave the '.self::dollars($current).' daily budget unchanged while the campaign is learning.'
                : 'Leave the budget unchanged while the campaign is learning.',
            CampaignDecisionVerdict::Watch => $current !== null
                ? 'Leave the '.self::dollars($current).' daily budget unchanged until the next check.'
                : 'Leave the budget unchanged until the next check.',
            CampaignDecisionVerdict::DataIssue => $current !== null
                ? 'Do not change the '.self::dollars($current).' daily budget until the data issue is fixed.'
                : 'Do not change the budget until the data issue is fixed.',
            CampaignDecisionVerdict::InsufficientData => $current !== null
                ? 'Do not change the '.self::dollars($current).' daily budget until there is enough data.'
                : 'Do not change the budget until there is enough data.',
        };
    }

    private static function changeSentence(
        string $verb,
        string $direction,
        int $changePercent,
        ?float $current,
        ?float $recommended,
        ?float $changeAmount,
    ): string {
        $magnitude = abs($changePercent);

        if ($magnitude === 0 || $current === null || $recommended === null || abs($changeAmount ?? 0) < 0.01) {
            if ($magnitude === 0) {
                return $verb.' the daily budget.';
            }

            if ($current !== null && $recommended === $current) {
                return sprintf('%s the daily budget by %d%%. Rounded, it stays at %s.', $verb, $magnitude, self::dollars($current));
            }

            return sprintf('%s the daily budget by %d%%.', $verb, $magnitude);
        }

        return sprintf(
            '%s the daily budget from %s to %s (%s %s per day).',
            $verb,
            self::dollars($current),
            self::dollars((float) $recommended),
            self::dollars(abs((float) $changeAmount)),
            $direction,
        );
    }

    private static function configuredPercent(CampaignDecisionVerdict $verdict): int
    {
        return match ($verdict) {
            CampaignDecisionVerdict::ScaleUp => (int) config('campaign-decisions.defaults.scale_up_percentage', 10),
            CampaignDecisionVerdict::DecreaseBudget => -(int) config('campaign-decisions.defaults.decrease_budget_percentage', 10),
            default => 0,
        };
    }

    private static function budgetOrNull(mixed $value): ?float
    {
        if (! is_numeric($value)) {
            return null;
        }

        $amount = round((float) $value, 2);

        return $amount > 0 ? $amount : null;
    }

    private static function dollars(float $amount): string
    {
        return '$'.number_format($amount, 2, '.', '');
    }

    /**
     * @return list<string>
     */
    private static function openingLabels(): array
    {
        return [
            'Decrease budget',
            'Scale up',
            'Pause',
            'Maintain',
            'Learning',
            'Watch',
            'Data issue',
            'Insufficient data',
        ];
    }
}
