<?php

namespace App\Campaigns;

use Throwable;

/**
 * Reuses a suggestion reply when the same prompt is asked and the stats have not changed.
 */
class CampaignPerformanceSuggestionReplyGuard
{
    public const SESSION_KEY = 'campaign_performance_chat_replies';

    /**
     * The suggest_campaign call from the current request, if it was a performance suggestion.
     *
     * @var array{campaign_id: string, from: ?string, to: ?string, hash: string}|null
     */
    private static ?array $current = null;

    public function forgetCurrent(): void
    {
        self::$current = null;
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    public function record(string $campaignId, string $focus, ?string $from, ?string $to, array $payload): void
    {
        if ($focus !== 'performance' || $campaignId === '') {
            return;
        }

        self::$current = [
            'campaign_id' => $campaignId,
            'from' => $from,
            'to' => $to,
            'hash' => $this->hash($payload),
        ];
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    public function hash(array $payload): string
    {
        $facts = [
            'from' => $payload['from'] ?? null,
            'to' => $payload['to'] ?? null,
            'campaign' => [
                'objective' => $payload['campaign']['objective'] ?? null,
                'region' => $payload['campaign']['region'] ?? null,
                'status' => $payload['campaign']['status'] ?? null,
                'effective_status' => $payload['campaign']['effective_status'] ?? null,
                'learning_status' => $payload['campaign']['learning_status'] ?? null,
                'daily_budget' => $payload['campaign']['daily_budget'] ?? null,
            ],
            'delivery' => $payload['delivery'] ?? null,
            'sales' => $payload['sales'] ?? null,
            'roi' => $payload['roi'] ?? null,
            'daily' => $payload['daily'] ?? null,
            'health' => $payload['health'] ?? null,
            'verdict' => [
                'verdict' => $payload['verdict']['verdict'] ?? null,
                'recommended_action' => $payload['verdict']['recommended_action'] ?? null,
                'recommended_budget_change_percent' => $payload['verdict']['recommended_budget_change_percent'] ?? null,
            ],
        ];

        return hash('sha256', (string) json_encode($this->canonical($facts)));
    }

    public function cachedReply(string $message, CampaignSuggestionReader $suggestions): ?string
    {
        $saved = $this->saved($message);

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

        try {
            $payload = $suggestions->forCampaign(
                'meta',
                $saved['campaign_id'],
                'performance',
                $saved['from'],
                $saved['to'],
            );
        } catch (Throwable) {
            return null;
        }

        if ($this->hash($payload) !== $saved['hash']) {
            return null;
        }

        return $saved['reply'];
    }

    public function store(string $message, string $reply): void
    {
        if (self::$current === null || trim($reply) === '') {
            return;
        }

        $saved = session(self::SESSION_KEY, []);
        $saved[$this->promptKey($message)] = [
            'campaign_id' => self::$current['campaign_id'],
            'from' => self::$current['from'],
            'to' => self::$current['to'],
            'hash' => self::$current['hash'],
            'reply' => $reply,
        ];

        session([self::SESSION_KEY => array_slice($saved, -20, null, true)]);
    }

    public function promptKey(string $message): string
    {
        $message = strtolower(trim($message));

        return preg_replace('/\s+/', ' ', $message) ?? $message;
    }

    /**
     * @return array{campaign_id: string, from: ?string, to: ?string, hash: string, reply: string}|null
     */
    private function saved(string $message): ?array
    {
        $saved = session(self::SESSION_KEY, []);
        $row = $saved[$this->promptKey($message)] ?? null;

        if (! is_array($row) || ! is_string($row['reply'] ?? null) || ! is_string($row['campaign_id'] ?? null) || ! is_string($row['hash'] ?? null)) {
            return null;
        }

        return [
            'campaign_id' => $row['campaign_id'],
            'from' => is_string($row['from'] ?? null) ? $row['from'] : null,
            'to' => is_string($row['to'] ?? null) ? $row['to'] : null,
            'hash' => $row['hash'],
            'reply' => $row['reply'],
        ];
    }

    private function canonical(mixed $value): mixed
    {
        if (! is_array($value)) {
            return $value;
        }

        if (array_is_list($value)) {
            return array_map($this->canonical(...), $value);
        }

        ksort($value);

        foreach ($value as $key => $item) {
            $value[$key] = $this->canonical($item);
        }

        return $value;
    }
}
