<?php

declare(strict_types=1);

namespace SeoScope\Repositories;

use PDO;

final class SeoAiTokenUsageRepository
{
    public function __construct(
        private PDO $pdo,
        private string $tablePrefix,
    ) {}

    public function record(int $userId, string $provider, int $inputTokens, int $outputTokens, int $totalTokens): void
    {
        if ($userId < 1) {
            return;
        }
        $provider = strtolower(trim($provider));
        if ($provider !== 'openai' && $provider !== 'anthropic') {
            return;
        }
        $inputTokens = max(0, $inputTokens);
        $outputTokens = max(0, $outputTokens);
        $totalTokens = max(0, $totalTokens);
        if ($totalTokens === 0 && $inputTokens + $outputTokens > 0) {
            $totalTokens = $inputTokens + $outputTokens;
        }
        if ($totalTokens === 0) {
            return;
        }

        $t = $this->table();
        $stmt = $this->pdo->prepare(
            "INSERT INTO {$t} (user_id, provider, input_tokens, output_tokens, total_tokens, created_at)
             VALUES (?, ?, ?, ?, ?, ?)"
        );
        $stmt->execute([
            $userId,
            $provider,
            $inputTokens,
            $outputTokens,
            $totalTokens,
            date('Y-m-d H:i:s'),
        ]);
    }

    /**
     * Sum total_tokens for rows with created_at >= $since (inclusive). $since null = no lower bound (all time).
     */
    public function sumTotalTokens(int $userId, string $provider, ?string $sinceDatetime): int
    {
        if ($userId < 1) {
            return 0;
        }
        $provider = strtolower(trim($provider));
        if ($provider !== 'openai' && $provider !== 'anthropic') {
            return 0;
        }
        $t = $this->table();
        if ($sinceDatetime !== null && $sinceDatetime !== '') {
            $stmt = $this->pdo->prepare(
                "SELECT COALESCE(SUM(total_tokens), 0) FROM {$t} WHERE user_id = ? AND provider = ? AND created_at >= ?"
            );
            $stmt->execute([$userId, $provider, $sinceDatetime]);

            return (int) $stmt->fetchColumn();
        }
        $stmt = $this->pdo->prepare(
            "SELECT COALESCE(SUM(total_tokens), 0) FROM {$t} WHERE user_id = ? AND provider = ?"
        );
        $stmt->execute([$userId, $provider]);

        return (int) $stmt->fetchColumn();
    }

    /** First moment of current calendar month (server default timezone). */
    public static function calendarMonthStart(): string
    {
        return date('Y-m-01 00:00:00');
    }

    private function table(): string
    {
        $prefix = $this->tablePrefix;
        if (!preg_match('/^[a-zA-Z0-9_]+$/', $prefix)) {
            $prefix = 'sscope_';
        }

        return '`' . str_replace('`', '``', $prefix . 'seo_ai_token_usage') . '`';
    }
}
