<?php

namespace App\Library\CampaignDecision;

class CampaignDecisionGuardrails
{
    /**
     * @param  array<string, mixed>  $combined
     * @param  array<string, float|int>  $settings
     * @return array{
     *     recommended_action: string,
     *     recommended_budget_change_percent: int,
     *     action_allowed: bool,
     *     guardrail: array<string, mixed>
     * }
     */
    public function apply(array $combined, array $settings): array
    {
        $verdict = $combined['verdict'];
        $percent = (int) ($combined['recommended_budget_change_percent'] ?? 0);
        $action = (string) ($combined['recommended_action'] ?? 'NONE');
        $notes = [];

        if ($verdict === CampaignDecisionVerdict::DataIssue || $verdict === CampaignDecisionVerdict::Learning) {
            return [
                'recommended_action' => 'NONE',
                'recommended_budget_change_percent' => 0,
                'action_allowed' => false,
                'guardrail' => ['blocked' => $verdict->value],
            ];
        }

        if ($percent > 0) {
            $cap = (int) ($settings['maximum_daily_budget_increase_percent'] ?? 20);
            if ($percent > $cap) {
                $notes[] = 'increase_capped';
                $percent = $cap;
            }
        }

        if ($percent < 0) {
            $cap = (int) ($settings['maximum_daily_budget_decrease_percent'] ?? 20);
            $magnitude = abs($percent);
            if ($magnitude > $cap) {
                $notes[] = 'decrease_capped';
                $percent = -$cap;
            }
        }

        $actionAllowed = ! in_array($verdict, [
            CampaignDecisionVerdict::DataIssue,
            CampaignDecisionVerdict::InsufficientData,
        ], true);

        return [
            'recommended_action' => $action,
            'recommended_budget_change_percent' => $percent,
            'action_allowed' => $actionAllowed,
            'guardrail' => ['notes' => $notes],
        ];
    }
}
