<?php

namespace WPSN\Modules\AI;

defined('ABSPATH') || exit;

final class AICallRepository
{
    /**
     * @param array<string, mixed> $row
     */
    public function insert(array $row): void
    {
        global $wpdb;
        $table = $wpdb->prefix . 'wpsn_ai_calls';

        $data = [
            'created_at'    => isset($row['created_at']) ? (string) $row['created_at'] : gmdate('Y-m-d H:i:s'),
            'provider'      => isset($row['provider']) ? (string) $row['provider'] : 'openai',
            'model'         => isset($row['model']) ? (string) $row['model'] : '',
            'purpose'       => isset($row['purpose']) ? (string) $row['purpose'] : '',
            'post_id'       => isset($row['post_id']) ? (int) $row['post_id'] : 0,
            'prompt_key'    => isset($row['prompt_key']) ? (string) $row['prompt_key'] : '',
            'prompt_version'=> isset($row['prompt_version']) ? (int) $row['prompt_version'] : 1,
            'prompt_hash'   => isset($row['prompt_hash']) ? (string) $row['prompt_hash'] : '',
            'tokens_in'     => isset($row['tokens_in']) ? (int) $row['tokens_in'] : 0,
            'tokens_out'    => isset($row['tokens_out']) ? (int) $row['tokens_out'] : 0,
            'tokens_total'  => isset($row['tokens_total']) ? (int) $row['tokens_total'] : 0,
            'cost_usd'      => isset($row['cost_usd']) ? (float) $row['cost_usd'] : 0.0,
            'latency_ms'    => isset($row['latency_ms']) ? (int) $row['latency_ms'] : 0,
            'success'       => !empty($row['success']) ? 1 : 0,
            'error_message' => isset($row['error_message']) ? (string) $row['error_message'] : '',
            'response_text' => isset($row['response_text']) ? (string) $row['response_text'] : '',
        ];

        $ok = $wpdb->insert($table, $data);

        // Backward compatibility / hardening:
        // If a site hasn't run the DB migration yet, new columns may not exist.
        // Retry without prompt_key/prompt_hash to avoid breaking the main flow.
        if ($ok === false && is_string($wpdb->last_error) && $wpdb->last_error !== '') {
            $err = (string) $wpdb->last_error;
            if (stripos($err, 'Unknown column') !== false) {
                $data2 = $data;
                unset($data2['prompt_key'], $data2['prompt_hash']);
                $wpdb->insert($table, $data2);
            }
        }
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    public function recent(int $limit = 50): array
    {
        global $wpdb;
        $table = $wpdb->prefix . 'wpsn_ai_calls';
        $limit = max(1, min(200, $limit));

        $rows = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM {$table} ORDER BY id DESC LIMIT %d",
                $limit
            ),
            ARRAY_A
        );

        return is_array($rows) ? $rows : [];
    }

    public function clear(): void
    {
        global $wpdb;
        $table = $wpdb->prefix . 'wpsn_ai_calls';
        $wpdb->query("TRUNCATE TABLE {$table}");
    }
}
