<?php

namespace App\Campaigns;

use App\Library\CampaignDecision\CampaignBudgetRecommendation;
use App\Library\CampaignDecision\CampaignDecisionVerdict;

/**
 * Single-campaign chat reply: metrics first, then the stored decision in readable labels.
 */
class CampaignPerformanceChatAnswer
{
    /**
     * Replace status codes in a chat reply so the page never shows snake_case verdicts.
     */
    public static function humanizeStatusCodes(string $text): string
    {
        $codes = self::statusCodes();

        if ($codes === []) {
            return $text;
        }

        $pattern = implode('|', array_map(fn (string $code): string => preg_quote($code, '/'), $codes));
        $text = preg_replace('/\s*\((?:'.$pattern.')\)/i', '', $text) ?? $text;

        $snake = array_values(array_filter($codes, fn (string $code): bool => str_contains($code, '_')));

        if ($snake !== []) {
            $snakePattern = implode('|', array_map(fn (string $code): string => preg_quote($code, '/'), $snake));
            $text = preg_replace_callback(
                '/\b(?:'.$snakePattern.')\b/i',
                fn (array $match): string => self::verdictLabel($match[0]) ?? $match[0],
                $text,
            ) ?? $text;
        }

        $words = array_values(array_filter($codes, fn (string $code): bool => ! str_contains($code, '_')));

        if ($words !== []) {
            $wordPattern = implode('|', array_map(fn (string $code): string => preg_quote($code, '/'), $words));
            $text = preg_replace_callback(
                '/(?<=:\s)(?:'.$wordPattern.')\b/i',
                fn (array $match): string => self::verdictLabel($match[0]) ?? $match[0],
                $text,
            ) ?? $text;
        }

        return $text;
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    public static function fromHealthPayload(array $payload): string
    {
        $lines = [];
        $name = self::text($payload['campaign'] ?? null);

        if ($name !== null) {
            $lines[] = '**'.$name.'**';
            $lines[] = '';
        }

        $identity = [];

        foreach ([
            'Campaign ID' => self::text($payload['campaign_id'] ?? null),
            'Account ID' => self::text($payload['account_id'] ?? null),
            'Platform' => self::platformLabel($payload['platform'] ?? null),
            'Platform status' => self::statusLabel($payload['platform_status'] ?? null),
        ] as $label => $value) {
            if ($value === null) {
                continue;
            }

            $identity[] = '- '.$label.': '.$value;
        }

        if ($identity !== []) {
            array_push($lines, ...$identity);
            $lines[] = '';
        }

        self::appendDelivery($lines, 'Meta delivery, last 7 days', $payload['last_7_days'] ?? null);
        self::appendDelivery($lines, 'Meta delivery, last 7 hours', $payload['last_7_hours'] ?? null);
        self::appendOutcomes($lines, data_get($payload, 'campaign_details.outcome_window'));
        self::appendDecision($lines, $payload);

        return self::humanizeStatusCodes(trim(implode("\n", $lines)));
    }

    /**
     * @param  list<string>  $lines
     * @param  array<string, mixed>  $payload
     */
    private static function appendDecision(array &$lines, array $payload): void
    {
        $stored = is_array($payload['stored_evaluation'] ?? null) ? $payload['stored_evaluation'] : [];
        $live = is_array($payload['live_evaluation'] ?? null) ? $payload['live_evaluation'] : [];
        $code = self::text($stored['verdict'] ?? null)
            ?? self::text($payload['verdict'] ?? null)
            ?? self::text($live['verdict'] ?? null);
        $label = self::verdictLabel($code);
        $summary = self::text($stored['action_summary'] ?? null) ?? self::text($payload['action_summary'] ?? null);

        if ($summary === null && $code !== null) {
            $verdict = CampaignDecisionVerdict::tryFromStored($code)
                ?? PerformanceVerdict::tryFromStored($code);
            $summary = $verdict?->actionSummary();
        }

        $budgetSummary = self::text(data_get($payload, 'budget_recommendation.summary'));

        if ($budgetSummary !== null) {
            $summary = $budgetSummary;
        }

        $reason = self::text($stored['verdict_reason'] ?? null) ?? self::text($payload['reason'] ?? null);
        $plan = self::withBudgetAmount(self::text($payload['implementation_plan'] ?? null), $budgetSummary);
        $savedDecision = self::withBudgetAmount(
            self::text($payload['decision'] ?? null) ?? self::text($payload['last_saved_reason'] ?? null),
            $budgetSummary,
        );

        if ($label !== null) {
            $lines[] = '**Verdict:** '.$label.($summary !== null ? ' — '.$summary : '');
            $lines[] = '';
        }

        if (is_numeric($payload['confidence'] ?? null)) {
            $lines[] = '**Confidence:** '.self::confidence($payload['confidence']);
            $lines[] = '';
        }

        if ($reason !== null) {
            $lines[] = '**Why this verdict:**';
            $lines[] = $reason;
            $lines[] = '';
        }

        if ($plan !== null) {
            $lines[] = '**What to do:**';
            $lines[] = $plan;
            $lines[] = '';
        } elseif ($savedDecision !== null) {
            $lines[] = '**What to do:**';
            $lines[] = $savedDecision;
            $lines[] = '';
            $savedDecision = null;
        }

        $savedStatus = self::verdictLabel(self::text($payload['saved_status'] ?? null));
        $aiStatus = self::verdictLabel(self::text($payload['ai_status'] ?? null));

        if ($savedStatus !== null) {
            $lines[] = '**Saved status:** '.$savedStatus;
        }

        if ($aiStatus !== null) {
            $lines[] = '**AI status:** '.$aiStatus;
        }

        if ($savedStatus !== null || $aiStatus !== null) {
            $lines[] = '';
        }

        if ($savedDecision !== null && $savedDecision !== $plan) {
            $lines[] = '**Saved decision:**';
            $lines[] = $savedDecision;
            $lines[] = '';
        }

        $liveCode = self::text($live['verdict'] ?? null);
        $liveLabel = self::verdictLabel($liveCode);
        $liveReason = self::text($live['reason'] ?? null);

        if ($liveLabel !== null && strcasecmp((string) $liveCode, (string) $code) !== 0) {
            $lines[] = '**Live re-check:** '.$liveLabel.($liveReason !== null ? ' — '.$liveReason : '');
        }
    }

    private static function withBudgetAmount(?string $text, ?string $summary): ?string
    {
        if ($text === null) {
            return null;
        }

        return CampaignBudgetRecommendation::applyToText($text, $summary);
    }

    private static function confidence(mixed $value): string
    {
        $formatted = number_format((float) $value, 2, '.', '');

        return rtrim(rtrim($formatted, '0'), '.');
    }

    /**
     * @return list<string>
     */
    private static function statusCodes(): array
    {
        $codes = array_merge(
            array_map(fn (CampaignDecisionVerdict $verdict): string => $verdict->value, CampaignDecisionVerdict::cases()),
            array_map(fn (PerformanceVerdict $verdict): string => $verdict->value, PerformanceVerdict::cases()),
            ['wait_learning', 'keep_running', 'investigate'],
        );

        $codes = array_values(array_unique($codes));
        usort($codes, fn (string $left, string $right): int => strlen($right) <=> strlen($left));

        return $codes;
    }

    private static function verdictLabel(?string $code): ?string
    {
        if ($code === null) {
            return null;
        }

        $verdict = CampaignDecisionVerdict::tryFromStored($code)
            ?? PerformanceVerdict::tryFromStored($code);

        if ($verdict !== null) {
            return $verdict->label();
        }

        return self::statusLabel($code);
    }

    /**
     * @param  list<string>  $lines
     */
    private static function appendDelivery(array &$lines, string $title, mixed $window): void
    {
        if (! is_array($window)) {
            return;
        }

        $metrics = array_filter([
            'Spend' => array_key_exists('spend', $window) ? self::money($window['spend']) : null,
            'Clicks' => array_key_exists('clicks', $window) ? self::count($window['clicks']) : null,
            'Impressions' => array_key_exists('impressions', $window) ? self::count($window['impressions']) : null,
        ], fn (?string $value): bool => $value !== null);

        if ($metrics === []) {
            return;
        }

        $range = self::rangeLabel($window['from'] ?? null, $window['to'] ?? null);
        $lines[] = '**'.($range === '' ? $title : $title.' ('.$range.')').'**';

        foreach ($metrics as $label => $value) {
            $lines[] = '- '.$label.': '.$value;
        }

        $lines[] = '';
    }

    /**
     * @param  list<string>  $lines
     */
    private static function appendOutcomes(array &$lines, mixed $window): void
    {
        if (! is_array($window)) {
            return;
        }

        $metrics = array_filter([
            'Spend' => array_key_exists('spend', $window) ? self::money($window['spend']) : null,
            'Orders' => array_key_exists('orders', $window) ? self::count($window['orders']) : null,
            'Sales' => array_key_exists('sales', $window) ? self::money($window['sales']) : null,
            'Conversions' => array_key_exists('conversions', $window) ? self::count($window['conversions']) : null,
            'Subscriptions' => array_key_exists('subscriptions', $window) ? self::count($window['subscriptions']) : null,
            'Installs' => array_key_exists('installs', $window) ? self::count($window['installs']) : null,
            'Bookings' => array_key_exists('bookings', $window) ? self::count($window['bookings']) : null,
            'Leads' => array_key_exists('leads', $window) ? self::count($window['leads']) : null,
        ], fn (?string $value): bool => $value !== null);

        if ($metrics === []) {
            return;
        }

        $range = self::rangeLabel($window['from'] ?? null, $window['to'] ?? null);
        $title = 'Lagged outcomes';
        $lines[] = '**'.($range === '' ? $title : $title.' ('.$range.')').'**';

        foreach ($metrics as $label => $value) {
            $lines[] = '- '.$label.': '.$value;
        }

        $lines[] = '';
    }

    private static function platformLabel(mixed $platform): ?string
    {
        $platform = self::text($platform);

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

        return match (strtolower($platform)) {
            'meta' => 'Meta',
            'google' => 'Google',
            'linkedin' => 'LinkedIn',
            default => self::statusLabel($platform),
        };
    }

    private static function statusLabel(mixed $status): ?string
    {
        $status = self::text($status);

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

        return str_replace('_', ' ', ucwords(strtolower($status)));
    }

    private static function rangeLabel(mixed $from, mixed $to): string
    {
        $start = self::timestampParts($from);
        $end = self::timestampParts($to);
        $keepClock = ($start['clock'] ?? null) !== null && ($start['clock'] !== '00:00' || ($end['clock'] ?? '00:00') !== '00:00')
            || ($end['clock'] ?? null) !== null && $end['clock'] !== '00:00';

        $startLabel = self::formatTimestamp($start, $keepClock);
        $endLabel = self::formatTimestamp($end, $keepClock);

        if ($startLabel === null) {
            return $endLabel ?? '';
        }

        if ($endLabel === null || $startLabel === $endLabel) {
            return $startLabel;
        }

        return $startLabel.' to '.$endLabel;
    }

    /**
     * @return array{date: string, clock: ?string}|null
     */
    private static function timestampParts(mixed $value): ?array
    {
        $value = self::text($value);

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

        if (preg_match('/^(\d{4}-\d{2}-\d{2})(?:[ T](\d{2}:\d{2})(?::\d{2})?)?/', $value, $match) !== 1) {
            return ['date' => $value, 'clock' => null];
        }

        return [
            'date' => $match[1],
            'clock' => $match[2] ?? null,
        ];
    }

    /**
     * @param  array{date: string, clock: ?string}|null  $parts
     */
    private static function formatTimestamp(?array $parts, bool $keepClock): ?string
    {
        if ($parts === null) {
            return null;
        }

        if (! $keepClock || $parts['clock'] === null) {
            return $parts['date'];
        }

        return $parts['date'].' '.$parts['clock'];
    }

    private static function money(mixed $value): ?string
    {
        if ($value === null || $value === '') {
            return null;
        }

        if (! is_numeric($value)) {
            return self::text($value);
        }

        return '$'.number_format((float) $value, 2);
    }

    private static function count(mixed $value): ?string
    {
        if ($value === null || $value === '') {
            return null;
        }

        if (! is_numeric($value)) {
            return self::text($value);
        }

        $number = (float) $value;

        if (floor($number) === $number) {
            return number_format($number, 0);
        }

        return number_format($number, 2);
    }

    private static function text(mixed $value): ?string
    {
        if (! is_string($value) && ! is_numeric($value)) {
            return null;
        }

        $value = trim((string) $value);

        return $value === '' ? null : $value;
    }
}
