<?php

namespace WPSN\Modules\AI;

defined('ABSPATH') || exit;

/**
 * Stores daily AI usage counters to enforce limits.
 */
final class AIUsageRepository
{
    public const OPTION_NAME = 'wpsn_ai_usage';

    /**
     * @return array<string, mixed>
     */
    public function getToday(): array
    {
        $value = get_option(self::OPTION_NAME);
        if (!is_array($value)) {
            $value = [];
        }

        $today = gmdate('Y-m-d');
        $date = isset($value['date']) ? (string) $value['date'] : '';

        if ($date !== $today) {
            $value = [
                'date'         => $today,
                'requests'     => 0,
                'tokens_in'    => 0,
                'tokens_out'   => 0,
                'tokens_total' => 0,
                'cost_usd'     => 0.0,
            ];
            update_option(self::OPTION_NAME, $value, false);
        }

        // Ensure keys exist.
        $value = array_merge(
            [
                'date'         => $today,
                'requests'     => 0,
                'tokens_in'    => 0,
                'tokens_out'   => 0,
                'tokens_total' => 0,
                'cost_usd'     => 0.0,
            ],
            $value
        );

        return $value;
    }

    public function reset(): void
    {
        update_option(self::OPTION_NAME, [
            'date'         => gmdate('Y-m-d'),
            'requests'     => 0,
            'tokens_in'    => 0,
            'tokens_out'   => 0,
            'tokens_total' => 0,
            'cost_usd'     => 0.0,
        ], false);
    }

    public function addUsage(int $requests, int $tokensIn, int $tokensOut, int $tokensTotal, float $costUsd): void
    {
        $cur = $this->getToday();

        $cur['requests'] = (int) ($cur['requests'] ?? 0) + max(0, $requests);
        $cur['tokens_in'] = (int) ($cur['tokens_in'] ?? 0) + max(0, $tokensIn);
        $cur['tokens_out'] = (int) ($cur['tokens_out'] ?? 0) + max(0, $tokensOut);
        $cur['tokens_total'] = (int) ($cur['tokens_total'] ?? 0) + max(0, $tokensTotal);
        $cur['cost_usd'] = (float) ($cur['cost_usd'] ?? 0.0) + max(0.0, $costUsd);

        update_option(self::OPTION_NAME, $cur, false);
    }
}
