<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Durable AI usage log for debugging, compliance, quota checks, and provider audits.
 */
class AIFLT_AI_Usage_Log {

    public static function table_name(): string {
        global $wpdb;
        return $wpdb->prefix . 'aiflt_ai_usage_log';
    }

    public static function maybe_create_table(): void {
        global $wpdb;
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        $table = esc_sql(self::table_name());
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE {$table} (
            id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            action_key VARCHAR(120) NOT NULL,
            provider VARCHAR(30) NOT NULL DEFAULT 'local',
            wrapper_code VARCHAR(190) DEFAULT NULL,
            model VARCHAR(120) DEFAULT NULL,
            status VARCHAR(30) NOT NULL DEFAULT 'unknown',
            message TEXT NULL,
            payload_hash CHAR(64) DEFAULT NULL,
            duration_ms INT UNSIGNED DEFAULT 0,
            prompt_tokens INT UNSIGNED DEFAULT 0,
            completion_tokens INT UNSIGNED DEFAULT 0,
            total_tokens INT UNSIGNED DEFAULT 0,
            estimated_cost DECIMAL(12,6) DEFAULT 0,
            site_user_id BIGINT(20) UNSIGNED DEFAULT NULL,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY action_key (action_key),
            KEY provider (provider),
            KEY status (status),
            KEY created_at (created_at)
        ) {$charset_collate};";
        dbDelta($sql);
    }

    public static function log(array $entry): void {
        global $wpdb;
        self::maybe_create_table();

        $data = [
            'action_key' => sanitize_key($entry['action_key'] ?? 'general'),
            'provider' => sanitize_key($entry['provider'] ?? 'local'),
            'wrapper_code' => isset($entry['wrapper_code']) ? sanitize_text_field((string) $entry['wrapper_code']) : null,
            'model' => isset($entry['model']) ? sanitize_text_field((string) $entry['model']) : null,
            'status' => sanitize_key($entry['status'] ?? 'unknown'),
            'message' => isset($entry['message']) ? sanitize_textarea_field((string) $entry['message']) : '',
            'payload_hash' => isset($entry['payload_hash']) ? sanitize_text_field((string) $entry['payload_hash']) : null,
            'duration_ms' => isset($entry['duration_ms']) ? absint($entry['duration_ms']) : 0,
            'prompt_tokens' => isset($entry['prompt_tokens']) ? absint($entry['prompt_tokens']) : 0,
            'completion_tokens' => isset($entry['completion_tokens']) ? absint($entry['completion_tokens']) : 0,
            'total_tokens' => isset($entry['total_tokens']) ? absint($entry['total_tokens']) : 0,
            'estimated_cost' => isset($entry['estimated_cost']) ? (float) $entry['estimated_cost'] : 0,
            'site_user_id' => get_current_user_id() ?: null,
            'created_at' => current_time('mysql'),
        ];

        $wpdb->insert(self::table_name(), $data, [
            '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%d', '%f', '%d', '%s'
        ]);
    }

    public static function get_monthly_total(string $month = ''): int {
        global $wpdb;
        self::maybe_create_table();
        $month = $month ?: gmdate('Y-m');
        $table = esc_sql(self::table_name());
        return (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} WHERE status = 'success' AND DATE_FORMAT(created_at, '%%Y-%%m') = %s",
            $month
        ));
    }

    public static function stats(int $days = 30): array {
        global $wpdb;
        self::maybe_create_table();
        $since = gmdate('Y-m-d H:i:s', strtotime('-' . absint($days) . ' days'));
        $table = esc_sql(self::table_name());
        $rows = $wpdb->get_results($wpdb->prepare(
            "SELECT provider, status, COUNT(*) total FROM {$table} WHERE created_at >= %s GROUP BY provider, status",
            $since
        ), ARRAY_A) ?: [];

        $stats = [
            'days' => absint($days),
            'total' => 0,
            'success' => 0,
            'error' => 0,
            'local' => 0,
            'by_provider' => [],
        ];
        foreach ($rows as $row) {
            $provider = sanitize_key($row['provider'] ?? 'unknown');
            $status = sanitize_key($row['status'] ?? 'unknown');
            $total = absint($row['total'] ?? 0);
            $stats['total'] += $total;
            if (isset($stats[$status])) {
                $stats[$status] += $total;
            }
            if (!isset($stats['by_provider'][$provider])) {
                $stats['by_provider'][$provider] = 0;
            }
            $stats['by_provider'][$provider] += $total;
        }
        return $stats;
    }

    public static function recent(int $limit = 20): array {
        global $wpdb;
        self::maybe_create_table();
        $limit = min(max(1, absint($limit)), 100);
        $table = esc_sql(self::table_name());
        return $wpdb->get_results(
            $wpdb->prepare("SELECT * FROM {$table} ORDER BY created_at DESC LIMIT %d", $limit),
            ARRAY_A
        ) ?: [];
    }
}
