<?php

namespace App\Campaigns;

use App\Campaigns\Platforms\MetaRules;
use App\Library\CampaignDecision\PlacementPublisherCosts;

/**
 * One card per ad set, with the same action, reason, and field list a creative card uses.
 */
class AdSetOptimizationCards
{
    /**
     * @param  array<string, mixed>  $optimization
     * @return list<array<string, mixed>>
     */
    public static function cards(array $optimization, string $posture = 'hold', string $context = '', string $platform = 'meta'): array
    {
        $cards = [];

        foreach (self::adSets($optimization) as $adSet) {
            $cards[] = self::card($adSet, $posture, $context, $platform);
        }

        return $cards;
    }

    /**
     * @param  array<string, mixed>  $optimization
     * @return list<array<string, mixed>>
     */
    public static function recommendations(array $optimization, string $posture = 'hold', string $context = '', string $platform = 'meta'): array
    {
        $recommendations = [];

        foreach (self::adSets($optimization) as $adSet) {
            array_push($recommendations, ...self::recommendationsFor($adSet, $posture, $context, $platform));
        }

        return $recommendations;
    }

    /**
     * @param  array<string, mixed>  $optimization
     * @return list<array<string, mixed>>
     */
    private static function adSets(array $optimization): array
    {
        $adSets = is_array($optimization['ad_sets'] ?? null) ? $optimization['ad_sets'] : [];
        $rows = [];

        foreach ($adSets as $adSet) {
            if (is_array($adSet)) {
                $rows[] = $adSet;
            }
        }

        return $rows;
    }

    /**
     * @param  array<string, mixed>  $adSet
     * @return array<string, mixed>
     */
    private static function card(array $adSet, string $posture, string $context = '', string $platform = 'meta'): array
    {
        $paused = self::isPaused($adSet);
        $recommendations = $paused ? [] : self::recommendationsFor($adSet, $posture, $context, $platform);
        $lead = self::lead($recommendations);
        $name = trim((string) ($adSet['name'] ?? ''));

        if ($name === '') {
            $name = trim((string) ($adSet['ad_set_id'] ?? 'Ad set'));
        }

        return [
            'ad_set_id' => trim((string) ($adSet['ad_set_id'] ?? '')),
            'name' => $name,
            'action' => self::cardAction($recommendations, $posture, $paused),
            'why' => $paused
                ? 'This ad set is paused on Meta. Stats stay on file; do not use them for live delivery or creative tests.'
                : self::cardWhy($adSet, $lead),
            'fields' => array_merge(self::factFields($adSet, $context, $platform), self::recommendationFields($recommendations)),
        ];
    }

    /**
     * @param  list<array<string, mixed>>  $recommendations
     */
    private static function cardAction(array $recommendations, string $posture, bool $paused = false): string
    {
        if ($paused) {
            return 'paused';
        }

        if ($posture === 'pause') {
            return 'pause';
        }

        foreach ($recommendations as $recommendation) {
            $label = (string) ($recommendation['label'] ?? '');
            $action = strtolower((string) ($recommendation['action'] ?? ''));

            if (in_array($label, ['Delivery', 'Advantage+'], true)) {
                return 'change';
            }

            if (str_contains($action, 'switch to lowest cost') || str_contains($action, 'fix delivery')) {
                return 'change';
            }
        }

        foreach ($recommendations as $recommendation) {
            $action = strtolower((string) ($recommendation['action'] ?? ''));

            if (str_starts_with($action, 'keep ') || str_contains($action, 'prefer advantage+')) {
                continue;
            }

            if ($action !== '') {
                return 'change';
            }
        }

        return 'keep';
    }

    /**
     * @param  list<array<string, mixed>>  $recommendations
     * @return array<string, mixed>
     */
    private static function lead(array $recommendations): array
    {
        foreach ($recommendations as $recommendation) {
            if (($recommendation['label'] ?? null) === 'Budget') {
                return $recommendation;
            }
        }

        return $recommendations[0] ?? [];
    }

    /**
     * @param  array<string, mixed>  $adSet
     * @param  array<string, mixed>  $lead
     */
    private static function cardWhy(array $adSet, array $lead): string
    {
        $why = is_string($lead['why'] ?? null) ? $lead['why'] : '';
        $learning = strtoupper(trim((string) ($adSet['learning_status'] ?? '')));

        if (in_array($learning, ['FAIL', 'LEARNING_LIMITED'], true) && ! str_contains($why, 'Learning status is')) {
            $prefix = 'Learning status is '.$learning.'.';

            return $why === '' ? $prefix : $prefix.' '.$why;
        }

        return $why;
    }

    /**
     * @param  array<string, mixed>  $adSet
     * @return list<array{label: string, value: string}>
     */
    private static function factFields(array $adSet, string $context = '', string $platform = 'meta'): array
    {
        $plat = strtolower(trim($platform));
        $platLabel = match ($plat) {
            'linkedin' => 'LinkedIn',
            'google' => 'Google',
            default => 'Meta',
        };
        $audience = is_array($adSet['audience'] ?? null) ? $adSet['audience'] : [];
        $bid = is_array($adSet['bid'] ?? null) ? $adSet['bid'] : [];
        $delivery = is_array($adSet['delivery'] ?? null) ? $adSet['delivery'] : [];
        $fields = [];
        $status = strtoupper(trim((string) ($adSet['status'] ?? '')));

        if ($status !== '') {
            $fields[] = ['label' => 'Status', 'value' => $status === 'PAUSED' || str_contains($status, 'PAUSED')
                ? 'Paused on Meta. Do not treat this ad set as live delivery.'
                : $status];
        }

        $type = trim((string) ($audience['type'] ?? ''));
        $signals = trim($context.' '.(string) ($adSet['name'] ?? ''));
        $retargeting = in_array(strtolower($type), ['retargeting', 'custom'], true);
        $suggested = AdSetAudienceAction::suggest($signals, $type, $plat);

        if ($suggested !== null) {
            $fields[] = ['label' => 'Audience', 'value' => $suggested];
        } elseif (strtolower($type) === 'broad') {
            $fields[] = ['label' => 'Audience', 'value' => 'Broad targeting is on file, so Meta is choosing who sees the ads. Keep it only if delivery is too thin to spend; otherwise add interests or job titles that match the landing-page offer.'];
        } elseif ($type !== '') {
            $fields[] = ['label' => 'Audience', 'value' => 'Keep the '.strtolower($type).' audience.'];
        }

        $included = self::includedAudienceLabels($audience);

        if ($included !== [] && $retargeting) {
            $fields[] = ['label' => 'Included', 'value' => 'Warm list: '.implode(', ', $included).'. Widen with longer windows or engagers; exclude people who already converted.'];
        } elseif ($included !== []) {
            $fields[] = ['label' => 'Included', 'value' => 'Included audiences: '.implode(', ', $included).'.'];
        }

        $size = self::audienceSizeValue($audience);

        if ($size !== null) {
            $fields[] = ['label' => 'Size', 'value' => 'Audience size on file is '.$size.'. If delivery is thin, the pool may be too small.'];
        }

        if (isset($delivery['cpm']) && is_numeric($delivery['cpm'])) {
            $fields[] = ['label' => 'CPM', 'value' => self::money($delivery['cpm'])];
        }

        if (isset($delivery['reach']) && is_numeric($delivery['reach'])) {
            $fields[] = ['label' => 'Reach', 'value' => number_format((int) $delivery['reach'])];
        }

        if (isset($delivery['frequency']) && is_numeric($delivery['frequency'])) {
            $fields[] = ['label' => 'Frequency', 'value' => number_format((float) $delivery['frequency'], 2)];
        }

        if (isset($delivery['landing_page_views']) && is_numeric($delivery['landing_page_views'])) {
            $lpv = (int) $delivery['landing_page_views'];
            $spend = is_numeric($delivery['spend'] ?? null) ? (float) $delivery['spend'] : null;
            $value = (string) $lpv;
            if ($lpv > 0 && $spend !== null && $spend > 0) {
                $value .= ' ('.self::money($spend / $lpv).' each)';
            }
            $fields[] = ['label' => 'Landing page views', 'value' => $value];
        }

        $learning = strtoupper(trim((string) ($adSet['learning_status'] ?? '')));

        if ($learning !== '') {
            $fields[] = ['label' => $platLabel.' learning', 'value' => $learning];
        }

        $strategy = strtoupper(trim((string) ($bid['bid_strategy'] ?? '')));

        if ($strategy !== '') {
            $fields[] = ['label' => 'Bidding strategy', 'value' => self::bidCopy($strategy)];
        }

        return $fields;
    }

    /**
     * @param  list<array<string, mixed>>  $recommendations
     * @return list<array{label: string, value: string}>
     */
    private static function recommendationFields(array $recommendations): array
    {
        $fields = [];

        foreach ($recommendations as $recommendation) {
            $label = trim((string) ($recommendation['label'] ?? ''));
            $action = trim((string) ($recommendation['action'] ?? ''));
            $value = $action;

            if ($label === '' || $value === '') {
                continue;
            }

            $fields[] = ['label' => $label, 'value' => $value];
        }

        return $fields;
    }

    /**
     * @param  array<string, mixed>  $adSet
     * @return list<array<string, mixed>>
     */
    private static function recommendationsFor(array $adSet, string $posture = 'hold', string $context = '', string $platform = 'meta'): array
    {
        $plat = strtolower(trim($platform));
        $platLabel = match ($plat) {
            'linkedin' => 'LinkedIn',
            'google' => 'Google',
            default => 'Meta',
        };
        $audience = is_array($adSet['audience'] ?? null) ? $adSet['audience'] : [];
        $delivery = is_array($adSet['delivery'] ?? null) ? $adSet['delivery'] : [];
        $bid = is_array($adSet['bid'] ?? null) ? $adSet['bid'] : [];
        $breakdowns = is_array($adSet['breakdowns'] ?? null) ? $adSet['breakdowns'] : [];
        $recommendations = [];
        $who = AdSetAudienceAction::who(trim($context.' '.(string) ($adSet['name'] ?? ''))) ?? '';
        $event = trim((string) ($adSet['optimization_event'] ?? ''));
        $goal = strtoupper(trim((string) ($adSet['optimization_goal'] ?? '')));
        $trafficGoal = $goal === 'LANDING_PAGE_VIEWS' || str_contains(strtolower($goal), 'traffic');
        $resultName = self::resultName($event, $goal, $trafficGoal);
        $spend = $delivery['spend'] ?? null;
        $resultCount = $trafficGoal
            ? ($delivery['landing_page_views'] ?? $delivery['outbound_clicks'] ?? null)
            : ($delivery['conversions'] ?? null);
        $spentWithoutResult = self::positiveAmount($spend) && self::storedZero($resultCount);

        $test = self::testName($who);

        if ($event !== '' || $goal !== '') {
            $eventLabel = $event !== '' ? $event : strtoupper($resultName);
            $eventAction = 'Judge '.$test.' on '.$eventLabel.'.';

            if ($goal !== '') {
                $eventAction .= ' The goal is '.$goal.'.';
            }

            $recommendations[] = self::recommendation(
                'Event',
                $eventAction,
                $goal !== ''
                    ? 'Optimization goal is '.$goal.($event !== '' ? ' and event is '.$event : '').'.'
                    : 'Optimization event is '.$event.'.',
                ['ad_set_id' => $adSet['ad_set_id'] ?? null, 'optimization_event' => $event !== '' ? $event : null, 'optimization_goal' => $goal !== '' ? $goal : null],
                'Uses the stored optimization goal instead of defaulting every campaign to conversions.',
                'high',
                'high',
            );
        }

        $budget = $bid['daily_budget'] ?? null;

        if (self::positiveAmount($budget) || $posture === 'pause') {
            $recommendations[] = self::recommendation(
                'Budget',
                self::budgetAction($posture, $who),
                'Daily budget on file is '.self::money($budget).'.',
                ['ad_set_id' => $adSet['ad_set_id'] ?? null, 'daily_budget' => is_numeric($budget) ? round((float) $budget, 2) : null],
                'Keeps the next test on the stored budget until it records a result.',
                'medium',
                'medium',
            );
        }

        $learning = strtoupper(trim((string) ($adSet['learning_status'] ?? '')));
        $strategy = strtoupper(trim((string) ($bid['bid_strategy'] ?? '')));

        if (in_array($learning, ['FAIL', 'LEARNING_LIMITED'], true) && ($spentWithoutResult || ! self::positiveAmount($spend))) {
            $budget = $bid['daily_budget'] ?? null;
            $why = $platLabel.' learning status is '.$learning.'. Spend is '.self::money($spend).' and '.$resultName.' are '.(is_numeric($resultCount) ? (string) $resultCount : '0').'.';

            if ($strategy !== '') {
                $why .= ' Bid strategy is '.$strategy.'.';
            }

            if (self::positiveAmount($budget) || self::storedZero($budget)) {
                $why .= ' Daily budget is '.self::money($budget).'.';
            }

            $costCap = self::isCostCap($strategy);
            $capAmount = isset($bid['bid_amount']) && is_numeric($bid['bid_amount'])
                ? round((float) $bid['bid_amount'], 2)
                : null;
            $bidAction = $costCap
                ? 'Step 1: switch to lowest cost (Highest volume)'
                    .($capAmount !== null ? ', or raise the $'.number_format($capAmount, 2).' cap' : '')
                    .'. Do not raise budget until it spends almost the full daily amount.'
                : 'Keep lowest cost. Do not add a cost cap while delivery is failing.';

            $recommendations[] = self::recommendation(
                'Delivery',
                $costCap
                    ? $bidAction
                    : 'Prefer lowest cost to restart. Check the bid limit and audience size. Do not assume ads are paused, rejected, or that payment failed. '.$bidAction,
                $why,
                [
                    'ad_set_id' => $adSet['ad_set_id'] ?? null,
                    'learning_status' => $adSet['learning_status'],
                    'spend' => $spend,
                    'result_count' => $resultCount,
                    'bid_strategy' => $strategy !== '' ? $strategy : null,
                    'bid_amount' => $capAmount,
                    'daily_budget' => is_numeric($budget) ? round((float) $budget, 2) : null,
                ],
                'Failed or limited learning with thin delivery is a delivery problem, not a creative test.',
                'high',
                'high',
            );
        }

        $type = strtolower(trim((string) ($audience['type'] ?? '')));

        if ($plat === 'meta' && ($audience['advantage_audience'] ?? null) === true && in_array($type, ['retargeting', 'lookalike'], true)) {
            $included = self::includedAudienceLabels($audience);
            $why = 'Advantage+ audience is on for a '.$type.' audience.';

            if ($included !== []) {
                $why .= ' Included audiences: '.implode(', ', $included).'.';
            }

            $size = self::audienceSizeText($audience);

            if ($size !== null) {
                $why .= ' '.$size;
            }

            $stay = $included !== [] ? implode(', ', $included) : 'the saved '.$type.' list';
            $recommendations[] = self::recommendation(
                'Advantage+',
                'Turn Advantage+ off so this list stays '.$stay.'. Put '.self::audienceName($who).' in its own ad set.',
                $why,
                [
                    'ad_set_id' => $adSet['ad_set_id'] ?? null,
                    'audience_type' => $type,
                    'advantage_audience' => true,
                    'audience_size_lower' => $audience['audience_size_lower'] ?? null,
                    'audience_size_upper' => $audience['audience_size_upper'] ?? null,
                    'included_audiences' => $included,
                ],
                'Shows when automated audience expansion is on for a narrow saved audience.',
                'medium',
                'medium',
            );
        }

        $placementRows = self::zeroResultRows($breakdowns['placements'] ?? [], 'label', $trafficGoal);

        if ($placementRows !== [] && $spentWithoutResult && ! $trafficGoal && $learning !== 'SUCCESS') {
            $placementAction = match ($plat) {
                'linkedin' => 'Prefer LinkedIn Audience Network on a low budget. Only trim a placement after it burns spend with no '.$resultName.'.',
                'google' => 'Prefer Search Partners and Display Network on a low budget. Only trim a network after it burns spend with no '.$resultName.'.',
                default => 'Prefer Advantage+ placements on a low budget. Only trim a placement after it burns spend with no '.$resultName.'.',
            };
            $recommendations[] = self::recommendation(
                'Placements',
                $plat === 'meta' || $plat === ''
                    ? self::placementAction($placementRows, $who, $event !== '' ? $event : $resultName)
                    : $placementAction,
                self::zeroResultText($placementRows, $resultName),
                ['ad_set_id' => $adSet['ad_set_id'] ?? null],
                'Names placements with spend and no optimization result, without cutting delivery on traffic campaigns.',
                'medium',
                'medium',
            );
        }

        if ($trafficGoal && self::positiveAmount($spend)) {
            $lpv = $delivery['landing_page_views'] ?? null;
            $costs = PlacementPublisherCosts::fromSnapshot([
                'ad_set_optimization' => ['ad_sets' => [$adSet]],
            ], 'traffic');
            $line = PlacementPublisherCosts::mustSay($costs);
            $placementKeepAction = match ($plat) {
                'linkedin' => 'Keep automated placements. Judge placements on landing page views and cost per landing page view, not conversions.',
                'google' => 'Keep automated network placements. Judge placements on landing page views and cost per landing page view, not conversions.',
                default => 'Keep Advantage+ placements. Judge placements on landing page views and cost per landing page view, not conversions.',
            };
            $recommendations[] = self::recommendation(
                'Placements',
                $line ?? $placementKeepAction,
                'Traffic goal is '.$goal.'. Landing page views on file: '.(is_numeric($lpv) ? (string) $lpv : 'not reported').'.',
                ['ad_set_id' => $adSet['ad_set_id'] ?? null, 'landing_page_views' => $lpv],
                'Compares Facebook and Instagram on cost per landing page view when those results are on file.',
                'high',
                'high',
            );
        }

        $countryRows = self::zeroResultRows($breakdowns['countries'] ?? [], 'country', $trafficGoal);

        if ($countryRows !== [] && $spentWithoutResult && ! $trafficGoal) {
            $recommendations[] = self::recommendation(
                'Country',
                self::countryAction($countryRows, $who, $event !== '' ? $event : $resultName),
                self::zeroResultText($countryRows, $resultName),
                ['ad_set_id' => $adSet['ad_set_id'] ?? null],
                'Names countries with spend and no optimization result.',
                'medium',
                'medium',
            );
        }

        return $recommendations;
    }

    private static function resultName(string $event, string $goal, bool $trafficGoal): string
    {
        if ($trafficGoal || $goal === 'LANDING_PAGE_VIEWS') {
            return 'landing page views';
        }

        if ($event !== '') {
            return strtolower(str_replace('_', ' ', $event));
        }

        return 'results';
    }

    /**
     * @param  array<string, mixed>  $audience
     * @return list<string>
     */
    private static function includedAudienceLabels(array $audience): array
    {
        $labels = [];

        foreach (is_array($audience['included_audiences'] ?? null) ? $audience['included_audiences'] : [] as $item) {
            if (! is_array($item)) {
                continue;
            }

            $label = trim((string) ($item['name'] ?? $item['id'] ?? ''));
            $subtype = trim((string) ($item['subtype'] ?? ''));

            if ($label === '') {
                continue;
            }

            $labels[] = $subtype !== '' ? "{$label} ({$subtype})" : $label;
        }

        return $labels;
    }

    /**
     * @param  array<string, mixed>  $audience
     */
    private static function audienceSizeValue(array $audience): ?string
    {
        $lower = $audience['audience_size_lower'] ?? null;
        $upper = $audience['audience_size_upper'] ?? null;

        if (is_numeric($lower) && is_numeric($upper)) {
            return (int) $lower.'-'.(int) $upper;
        }

        if (is_numeric($lower) || is_numeric($upper)) {
            return (string) (int) (is_numeric($lower) ? $lower : $upper);
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $audience
     */
    private static function audienceSizeText(array $audience): ?string
    {
        $size = self::audienceSizeValue($audience);

        return $size === null ? null : 'Audience size on file is '.$size.'.';
    }

    /**
     * @return list<array{label: string, spend: mixed}>
     */
    private static function zeroResultRows(mixed $rows, string $labelKey, bool $trafficGoal = false): array
    {
        if (! is_array($rows)) {
            return [];
        }

        $quiet = [];

        foreach ($rows as $row) {
            if (! is_array($row) || ! self::positiveAmount($row['spend'] ?? null)) {
                continue;
            }

            $result = $trafficGoal
                ? ($row['landing_page_views'] ?? $row['outbound_clicks'] ?? $row['conversions'] ?? null)
                : ($row['conversions'] ?? null);

            if (! self::storedZero($result)) {
                continue;
            }

            $label = trim((string) ($row[$labelKey] ?? $row['label'] ?? ''));

            if ($label === '') {
                continue;
            }

            $quiet[] = ['label' => $label, 'spend' => $row['spend']];
        }

        usort($quiet, fn (array $left, array $right): int => ((float) $right['spend']) <=> ((float) $left['spend']));

        return array_slice($quiet, 0, 3);
    }

    /**
     * @return list<array{label: string, spend: mixed}>
     */
    private static function zeroConversionRows(mixed $rows, string $labelKey): array
    {
        return self::zeroResultRows($rows, $labelKey, false);
    }

    /**
     * @param  list<array{label: string, spend: mixed}>  $rows
     */
    private static function zeroResultText(array $rows, string $resultName): string
    {
        $parts = [];

        foreach ($rows as $row) {
            $parts[] = $row['label'].' spent '.self::money($row['spend']).' with 0 '.$resultName;
        }

        return implode('. ', $parts).'.';
    }

    /**
     * @param  list<array{label: string, spend: mixed}>  $rows
     */
    private static function zeroConversionText(array $rows): string
    {
        return self::zeroResultText($rows, 'conversions');
    }

    /**
     * @param  list<string>  $labels
     */
    private static function joinLabels(array $labels): string
    {
        $labels = array_values(array_filter($labels, fn (string $label): bool => $label !== ''));
        $count = count($labels);

        if ($count < 2) {
            return $labels[0] ?? '';
        }

        if ($count === 2) {
            return $labels[0].' and '.$labels[1];
        }

        $last = array_pop($labels);

        return implode(', ', $labels).', and '.$last;
    }

    private static function budgetAction(string $posture, string $who = ''): string
    {
        $test = self::testName($who);

        return match ($posture) {
            'pause' => 'Pause this ad set, then restart only '.$test.' after the ad and the page ask for the same result.',
            'decrease' => 'Move the reduced budget onto '.$test.'.',
            default => 'Use this budget for '.$test.'. Add spend only after that test records a result.',
        };
    }

    private static function testName(string $who): string
    {
        return $who === '' ? 'the next test' : 'the test for '.$who;
    }

    private static function audienceName(string $who): string
    {
        return $who === '' ? 'the next audience' : 'the '.$who.' audience';
    }

    /**
     * @param  list<array{label: string, spend: mixed}>  $rows
     */
    private static function placementAction(array $rows, string $who, string $event): string
    {
        $lead = $rows[0];
        $result = $event !== '' ? $event : 'a conversion';
        $action = 'Run '.self::testName($who).' on '.$lead['label'].' first ('.self::money($lead['spend']).' already delivered there).';
        $rest = array_column(array_slice($rows, 1), 'label');

        if ($rest === []) {
            return $action.' Judge it on '.$result.' before adding another placement.';
        }

        return $action.' Hold '.self::joinLabels($rest).' until '.$lead['label'].' records '.$result.'.';
    }

    /**
     * @param  list<array{label: string, spend: mixed}>  $rows
     */
    private static function countryAction(array $rows, string $who, string $event): string
    {
        $lead = $rows[0];
        $result = $event !== '' ? $event : 'a conversion';

        return 'Start '.self::testName($who).' in '.$lead['label'].', where '.self::money($lead['spend']).' was already spent. Add another country only after '.$lead['label'].' records '.$result.'.';
    }

    /**
     * @param  array<string, mixed>  $adSet
     */
    private static function isPaused(array $adSet): bool
    {
        $status = strtoupper(trim((string) ($adSet['status'] ?? '')));

        return $status === 'PAUSED' || str_contains($status, 'PAUSED');
    }

    private static function bidCopy(string $strategy): string
    {
        $copy = app(MetaRules::class)->bidStrategyCopy($strategy);

        return $copy ?? strtoupper(trim($strategy));
    }

    private static function isCostCap(string $strategy): bool
    {
        if ($strategy === '' || str_contains($strategy, 'WITHOUT_CAP')) {
            return false;
        }

        return str_contains($strategy, 'COST_CAP')
            || str_contains($strategy, 'BID_CAP')
            || str_contains($strategy, 'TARGET_COST');
    }

    private static function positiveAmount(mixed $value): bool
    {
        return is_numeric($value) && (float) $value > 0;
    }

    private static function storedZero(mixed $value): bool
    {
        return is_numeric($value) && (float) $value === 0.0;
    }

    private static function money(mixed $value): string
    {
        return '$'.number_format(is_numeric($value) ? (float) $value : 0, 2);
    }

    /**
     * @param  array<string, mixed>  $supporting
     * @return array<string, mixed>
     */
    private static function recommendation(string $label, string $action, string $why, array $supporting, string $impact, string $confidence, string $priority): array
    {
        return [
            'label' => $label,
            'action' => $action,
            'why' => $why,
            'supporting_data' => $supporting,
            'expected_impact' => $impact,
            'confidence' => $confidence,
            'priority' => $priority,
        ];
    }
}
