<?php
/**
 * Statistics Buffer Service
 *
 * Buffers cache statistics in memory and flushes to database periodically
 * to minimize database writes during high-traffic periods.
 *
 * @package Mamba\Modules\Caching\Services
 * @since   1.0.0
 */

namespace Mamba\Modules\Caching\Services;

use Mamba\Support\CacheAdapter;
use Exception;

/**
 * Class StatsBuffer
 *
 * In-memory buffer for cache statistics that batches database writes
 * for improved performance. Supports both aggregate and daily statistics.
 *
 * @since 1.0.0
 */
final class StatsBuffer {
    private static $hits = 0;
    private static $misses = 0;
    private static $byType = [
        'product' => ['hits' => 0, 'misses' => 0],
        'category' => ['hits' => 0, 'misses' => 0],
        'shop' => ['hits' => 0, 'misses' => 0],
        'store_api' => ['hits' => 0, 'misses' => 0],
        'other' => ['hits' => 0, 'misses' => 0],
        'homepage' => ['hits' => 0, 'misses' => 0],
    ];
    private static $generationMs = 0;
    private static $generationCount = 0;
    private static $storeApiGenerationMs = 0;
    private static $storeApiGenerationCount = 0;
    
    // Daily stats buffering
    private static $dailyHits = 0;
    private static $dailyMisses = 0;
    private static $dailyByType = [
        'product' => ['hits' => 0, 'misses' => 0],
        'category' => ['hits' => 0, 'misses' => 0],
        'shop' => ['hits' => 0, 'misses' => 0],
        'store_api' => ['hits' => 0, 'misses' => 0],
        'other' => ['hits' => 0, 'misses' => 0],
        'homepage' => ['hits' => 0, 'misses' => 0],
    ];
    private static $dailyGenerationMs = 0;
    private static $dailyGenerationCount = 0;

    public static function hit(string $type = 'other'): void {
        self::$hits++;
        $type = self::normalizeType($type);
        self::$byType[$type]['hits']++;
        
        // Use atomic increment for proper accumulation across requests
        self::incrementAccumulatedHit($type);
        self::incrementDailyHit($type);
        
        // Debug: Log when we record a hit
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Mamba StatsBuffer: Recorded hit for type: ' . $type . ' (total hits: ' . self::$hits . ')');
        }
    }

    public static function miss(string $type = 'other', int $generationMs = 0): void {
        self::$misses++;
        $type = self::normalizeType($type);
        self::$byType[$type]['misses']++;
        
        // Validate generation time before recording (prevent invalid data)
        if ($generationMs > 0 && $generationMs < 30000) { // Max 30 seconds, min 1ms
            if ($type === 'store_api') {
                self::$storeApiGenerationMs += $generationMs;
                self::$storeApiGenerationCount++;
            } else {
                self::$generationMs += $generationMs;
                self::$generationCount++;
            }
        }
        
        // Use atomic increment for proper accumulation across requests
        self::incrementAccumulatedMiss($type, $generationMs);
        self::incrementDailyMiss($type, $generationMs);
        
        // Debug: Log when we record a miss
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Mamba StatsBuffer: Recorded miss for type: ' . $type . ' (total misses: ' . self::$misses . ')');
        }
    }
    
    public static function dailyHit(string $type = 'other'): void {
        self::$dailyHits++;
        $type = self::normalizeType($type);
        self::$dailyByType[$type]['hits']++;
    }
    
    public static function dailyMiss(string $type = 'other', int $generationMs = 0): void {
        self::$dailyMisses++;
        $type = self::normalizeType($type);
        self::$dailyByType[$type]['misses']++;
        
        // Validate generation time before recording (prevent invalid data)
        if ($generationMs > 0 && $generationMs < 30000) { // Max 30 seconds, min 1ms
            self::$dailyGenerationMs += $generationMs;
            self::$dailyGenerationCount++;
        }
    }

    public static function schedule(): void {
        // Use the unique mamba_minutely schedule (registered in Controller)
        if (!wp_next_scheduled('mamba_stats_flush')) {
            wp_schedule_event(time() + 30, 'mamba_minutely', 'mamba_stats_flush');
        }
    }

    public static function flushNow(): void {
        // Check for concurrent flush lock
        $lockKey = 'mamba_stats_flush_lock';
        $lockValue = time();
        $existingLock = get_transient($lockKey);
        
        if ($existingLock && (time() - $existingLock) < 30) {
            // Another flush is in progress, skip this one
            return;
        }
        
        // Set lock with 30-second TTL
        set_transient($lockKey, $lockValue, 30);
        
        try {
            // Read all accumulated stats from cache (new atomic system)
            $accumulated = self::readAllAccumulatedStats();
            $accumulated = self::validateAccumulatedStats($accumulated);
            
            if ($accumulated['hits'] === 0 && $accumulated['misses'] === 0) {
                // Nothing to flush
                return;
        }
        
        // Debug: Log when we're flushing stats
            self::logStatsOperation('flush_stats', [
                'hits' => $accumulated['hits'],
                'misses' => $accumulated['misses'],
                'generation_ms' => $accumulated['generation_ms']
            ]);

            // Get current persistent stats
        $stats = get_option('mamba_cache_stats', self::getDefaultStats());
        
            // Validate stats structure before updating
            $stats = self::validateStatsStructure($stats);
            
            // Update main stats with accumulated data
            $stats['cache_hits'] = max(0, (int)($stats['cache_hits'] ?? 0) + $accumulated['hits']);
            $stats['cache_misses'] = max(0, (int)($stats['cache_misses'] ?? 0) + $accumulated['misses']);
            
            // Update by-type stats with accumulated data
            foreach ($accumulated['by_type'] as $type => $counts) {
            if (!isset($stats['by_type'][$type])) {
                $stats['by_type'][$type] = ['hits' => 0, 'misses' => 0];
            }
                
                $stats['by_type'][$type]['hits'] = max(0, (int)($stats['by_type'][$type]['hits'] ?? 0) + $counts['hits']);
                $stats['by_type'][$type]['misses'] = max(0, (int)($stats['by_type'][$type]['misses'] ?? 0) + $counts['misses']);
            }
            
            // Update generation stats with accumulated data
            if ($accumulated['generation_ms'] > 0) {
                $stats['gen']['total_ms'] = max(0, (int)($stats['gen']['total_ms'] ?? 0) + $accumulated['generation_ms']);
                $stats['gen']['misses'] = max(0, (int)($stats['gen']['misses'] ?? 0) + $accumulated['generation_count']);
            }
            
            // Update Store API generation stats with accumulated data
            if ($accumulated['store_api_generation_ms'] > 0) {
            if (!isset($stats['gen_store_api'])) {
                $stats['gen_store_api'] = ['total_ms' => 0, 'misses' => 0];
                }
                $stats['gen_store_api']['total_ms'] = max(0, (int)($stats['gen_store_api']['total_ms'] ?? 0) + $accumulated['store_api_generation_ms']);
                $stats['gen_store_api']['misses'] = max(0, (int)($stats['gen_store_api']['misses'] ?? 0) + $accumulated['store_api_generation_count']);
            }
            
            // Atomic update with validation
            $updateSuccess = update_option('mamba_cache_stats', $stats, false);
            
            if (!$updateSuccess && defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Mamba StatsBuffer: Failed to update stats');
            }
            
            // Reset accumulated stats after successful flush
            if ($updateSuccess) {
                self::resetAccumulatedStats();
            }
            
            // Flush daily stats
            self::flushDailyStats();
            
        } finally {
            // Always clear the flush lock
        delete_transient($lockKey);
        
        // Reset current request counters
            self::resetCounters();
        }
    }
    
    public static function flushDailyStats(): void {
        // Read accumulated daily stats from cache
        $dailyAccumulated = self::readDailyAccumulatedStats();
        $dailyAccumulated = self::validateAccumulatedStats($dailyAccumulated);
        
        if ($dailyAccumulated['hits'] === 0 && $dailyAccumulated['misses'] === 0) {
            return; // Nothing to flush
        }
        
        // Check if we should throttle writes (every 60 seconds)
        $lastWrite = (int)get_option('mamba_stats_last_write', 0);
        $now = time();
        if (($now - $lastWrite) < 60) {
            return; // Throttle writes to every 60 seconds
        }
        
        $today = wp_date('Y-m-d');
        $daily = get_option('mamba_daily_stats', []);
        if (!is_array($daily)) $daily = [];
        
        // Find or create today's entry
        $todayIndex = self::findOrCreateTodayEntry($daily, $today);
        
        // Update today's stats with accumulated data
        $daily[$todayIndex]['hits'] += $dailyAccumulated['hits'];
        $daily[$todayIndex]['misses'] += $dailyAccumulated['misses'];
        
        // Update by-type daily stats
        foreach ($dailyAccumulated['by_type'] as $type => $counts) {
            $daily[$todayIndex]['by_type'][$type]['hits'] += $counts['hits'];
            $daily[$todayIndex]['by_type'][$type]['misses'] += $counts['misses'];
        }
        
        // Update generation stats
        if ($dailyAccumulated['generation_ms'] > 0) {
            $daily[$todayIndex]['gen']['total_ms'] += $dailyAccumulated['generation_ms'];
            $daily[$todayIndex]['gen']['misses'] += $dailyAccumulated['generation_count'];
        }
        
        // Save updated daily stats
        update_option('mamba_daily_stats', $daily, false);
        update_option('mamba_stats_last_write', $now, false);
        
        // Also update object cache for faster access
        if (class_exists('\Mamba\Support\CacheAdapter')) {
            \Mamba\Support\CacheAdapter::set('daily_stats_' . $today, $daily[$todayIndex], 'mamba_stats', 24 * HOUR_IN_SECONDS);
        }
        
        // Reset daily accumulated stats
        self::resetDailyAccumulatedStats();
        
        // Also reset in-memory daily counters (for backward compatibility)
        self::$dailyHits = 0;
        self::$dailyMisses = 0;
        self::$dailyByType = [
            'product' => ['hits' => 0, 'misses' => 0],
            'category' => ['hits' => 0, 'misses' => 0],
            'shop' => ['hits' => 0, 'misses' => 0],
            'store_api' => ['hits' => 0, 'misses' => 0],
            'other' => ['hits' => 0, 'misses' => 0],
            'homepage' => ['hits' => 0, 'misses' => 0],
        ];
        self::$dailyGenerationMs = 0;
        self::$dailyGenerationCount = 0;
    }
    
    /**
     * Find or create today's entry in daily stats
     */
    private static function findOrCreateTodayEntry(array &$daily, string $today): int {
        // Find today's entry
        $todayIndex = -1;
        foreach ($daily as $i => $entry) {
            if ($entry['date'] === $today) {
                $todayIndex = $i;
                break;
            }
        }
        
        if ($todayIndex === -1) {
            // Create new day entry
            if (!empty($daily) && count($daily) >= 30) {
                array_shift($daily); // Keep only 30 days
            }
            $daily[] = [
                'date' => $today,
                'hits' => 0,
                'misses' => 0,
                'by_type' => [
                    'product' => ['hits' => 0, 'misses' => 0],
                    'category' => ['hits' => 0, 'misses' => 0],
                    'shop' => ['hits' => 0, 'misses' => 0],
                    'store_api' => ['hits' => 0, 'misses' => 0],
                    'other' => ['hits' => 0, 'misses' => 0],
                    'homepage' => ['hits' => 0, 'misses' => 0],
                ],
                'gen' => ['total_ms' => 0, 'misses' => 0],
            ];
            $todayIndex = count($daily) - 1;
        }
        
        return $todayIndex;
    }

    private static function normalizeType(string $type): string {
        $allowed = ['product', 'category', 'shop', 'store_api', 'other', 'homepage'];
        return in_array($type, $allowed, true) ? $type : 'other';
    }
    
    /**
     * Clear accumulated stats from persistent storage (legacy method - now uses resetAccumulatedStats)
     */
    private static function clearAccumulatedStats(): void {
        self::resetAccumulatedStats();
    }
    
    /**
     * Get default stats structure
     */
    private static function getDefaultStats(): array {
        return [
            'cache_hits' => 0,
            'cache_misses' => 0,
            'cache_size' => 0,
            'last_cleared' => 0,
            'by_type' => [
                'product' => ['hits' => 0, 'misses' => 0],
                'category' => ['hits' => 0, 'misses' => 0],
                'shop' => ['hits' => 0, 'misses' => 0],
                'store_api' => ['hits' => 0, 'misses' => 0],
                'other' => ['hits' => 0, 'misses' => 0],
                'homepage' => ['hits' => 0, 'misses' => 0],
            ],
            'gen' => ['total_ms' => 0, 'misses' => 0],
            'gen_store_api' => ['total_ms' => 0, 'misses' => 0],
        ];
    }

    /**
     * Validate and ensure stats structure is correct.
     */
    private static function validateStatsStructure(array $stats): array {
        // Ensure 'cache_hits' and 'cache_misses' are integers
        $stats['cache_hits'] = (int)($stats['cache_hits'] ?? 0);
        $stats['cache_misses'] = (int)($stats['cache_misses'] ?? 0);

        // Ensure 'by_type' is an array and has all expected types
        if (!isset($stats['by_type']) || !is_array($stats['by_type'])) {
            $stats['by_type'] = self::getDefaultStats()['by_type']; // Fallback to default
        } else {
            foreach (self::$byType as $type => $counts) {
                if (!isset($stats['by_type'][$type])) {
                    $stats['by_type'][$type] = ['hits' => 0, 'misses' => 0];
                }
            }
        }

        // Ensure 'gen' is an array and has 'total_ms' and 'misses'
        if (!isset($stats['gen']) || !is_array($stats['gen'])) {
            $stats['gen'] = self::getDefaultStats()['gen']; // Fallback to default
        }

        // Ensure 'gen_store_api' is an array and has 'total_ms' and 'misses'
        if (!isset($stats['gen_store_api']) || !is_array($stats['gen_store_api'])) {
            $stats['gen_store_api'] = self::getDefaultStats()['gen_store_api']; // Fallback to default
        }

        return $stats;
    }

    /**
     * Reset current request counters.
     */
    private static function resetCounters(): void {
        self::$hits = 0;
        self::$misses = 0;
        self::$byType = [
            'product' => ['hits' => 0, 'misses' => 0],
            'category' => ['hits' => 0, 'misses' => 0],
            'shop' => ['hits' => 0, 'misses' => 0],
            'store_api' => ['hits' => 0, 'misses' => 0],
            'other' => ['hits' => 0, 'misses' => 0],
            'homepage' => ['hits' => 0, 'misses' => 0],
        ];
        self::$generationMs = 0;
        self::$generationCount = 0;
        self::$storeApiGenerationMs = 0;
        self::$storeApiGenerationCount = 0;
    }

    /**
     * Atomic increment methods for proper stats accumulation
     */
    private static function incrementAccumulatedHit(string $type): void {
        try {
            if (class_exists('\Mamba\Support\CacheAdapter')) {
                // Atomic increment for total hits
                \Mamba\Support\CacheAdapter::increment('accumulated_hits', 'mamba_stats', 1);
                
                // Atomic increment for type-specific hits
                \Mamba\Support\CacheAdapter::increment("accumulated_{$type}_hits", 'mamba_stats', 1);
            }
        } catch (Exception $e) {
            // Fallback to file-based accumulation
            self::fallbackAccumulation('hit', $type);
        }
    }
    
    private static function incrementAccumulatedMiss(string $type, int $generationMs = 0): void {
        try {
            if (class_exists('\Mamba\Support\CacheAdapter')) {
                // Atomic increment for total misses
                \Mamba\Support\CacheAdapter::increment('accumulated_misses', 'mamba_stats', 1);
                
                // Atomic increment for type-specific misses
                \Mamba\Support\CacheAdapter::increment("accumulated_{$type}_misses", 'mamba_stats', 1);
                
                // Atomic increment for generation time
                if ($generationMs > 0) {
                    \Mamba\Support\CacheAdapter::increment('accumulated_generation_ms', 'mamba_stats', $generationMs);
                    \Mamba\Support\CacheAdapter::increment('accumulated_generation_count', 'mamba_stats', 1);
                    
                    // Store API specific generation time
                    if ($type === 'store_api') {
                        \Mamba\Support\CacheAdapter::increment('accumulated_store_api_generation_ms', 'mamba_stats', $generationMs);
                        \Mamba\Support\CacheAdapter::increment('accumulated_store_api_generation_count', 'mamba_stats', 1);
                    }
                }
            }
        } catch (Exception $e) {
            // Fallback to file-based accumulation
            self::fallbackAccumulation('miss', $type, $generationMs);
        }
    }
    
    private static function incrementDailyHit(string $type): void {
        try {
            if (class_exists('\Mamba\Support\CacheAdapter')) {
                $today = wp_date('Y-m-d');
                
                // Atomic increment for daily total hits
                \Mamba\Support\CacheAdapter::increment("daily_{$today}_hits", 'mamba_stats', 1);
                
                // Atomic increment for daily type-specific hits
                \Mamba\Support\CacheAdapter::increment("daily_{$today}_{$type}_hits", 'mamba_stats', 1);
            }
        } catch (Exception $e) {
            // Fallback to in-memory daily stats (existing behavior)
        }
    }
    
    private static function incrementDailyMiss(string $type, int $generationMs = 0): void {
        try {
            if (class_exists('\Mamba\Support\CacheAdapter')) {
                $today = wp_date('Y-m-d');
                
                // Atomic increment for daily total misses
                \Mamba\Support\CacheAdapter::increment("daily_{$today}_misses", 'mamba_stats', 1);
                
                // Atomic increment for daily type-specific misses
                \Mamba\Support\CacheAdapter::increment("daily_{$today}_{$type}_misses", 'mamba_stats', 1);
                
                // Atomic increment for daily generation time
                if ($generationMs > 0) {
                    \Mamba\Support\CacheAdapter::increment("daily_{$today}_generation_ms", 'mamba_stats', $generationMs);
                    \Mamba\Support\CacheAdapter::increment("daily_{$today}_generation_count", 'mamba_stats', 1);
                }
            }
        } catch (Exception $e) {
            // Fallback to in-memory daily stats (existing behavior)
        }
    }
    
    /**
     * Fallback accumulation using file system
     */
    private static function fallbackAccumulation(string $action, string $type, int $generationMs = 0): void {
        try {
            $fallbackFile = WP_CONTENT_DIR . '/cache/mamba/stats_fallback.json';
            $fallbackData = [];
            
            if (file_exists($fallbackFile)) {
                $fallbackData = json_decode(file_get_contents($fallbackFile), true) ?: [];
            }
            
            // Initialize structure if needed
            if (!isset($fallbackData['by_type'])) {
                $fallbackData['by_type'] = [
                    'product' => ['hits' => 0, 'misses' => 0],
                    'category' => ['hits' => 0, 'misses' => 0],
                    'shop' => ['hits' => 0, 'misses' => 0],
                    'store_api' => ['hits' => 0, 'misses' => 0],
                    'other' => ['hits' => 0, 'misses' => 0],
                    'homepage' => ['hits' => 0, 'misses' => 0],
                ];
            }
            
            // Update fallback data
            if ($action === 'hit') {
                $fallbackData['hits'] = ($fallbackData['hits'] ?? 0) + 1;
                $fallbackData['by_type'][$type]['hits'] = ($fallbackData['by_type'][$type]['hits'] ?? 0) + 1;
            } elseif ($action === 'miss') {
                $fallbackData['misses'] = ($fallbackData['misses'] ?? 0) + 1;
                $fallbackData['by_type'][$type]['misses'] = ($fallbackData['by_type'][$type]['misses'] ?? 0) + 1;
                
                if ($generationMs > 0) {
                    $fallbackData['generation_ms'] = ($fallbackData['generation_ms'] ?? 0) + $generationMs;
                    $fallbackData['generation_count'] = ($fallbackData['generation_count'] ?? 0) + 1;
                    
                    if ($type === 'store_api') {
                        $fallbackData['store_api_generation_ms'] = ($fallbackData['store_api_generation_ms'] ?? 0) + $generationMs;
                        $fallbackData['store_api_generation_count'] = ($fallbackData['store_api_generation_count'] ?? 0) + 1;
                    }
                }
            }
            
            // Save fallback data atomically
            $tmpFile = $fallbackFile . '.tmp';
            if (file_put_contents($tmpFile, json_encode($fallbackData)) !== false) {
                rename($tmpFile, $fallbackFile);
            }
            
        } catch (Exception $e) {
            // Silently fail - fallback accumulation failed
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Mamba: Fallback accumulation failed: ' . $e->getMessage());
            }
        }
    }

    /**
     * Read all accumulated stats from cache
     */
    private static function readAllAccumulatedStats(): array {
        $accumulated = [
                'hits' => 0,
                'misses' => 0,
                'by_type' => [
                    'product' => ['hits' => 0, 'misses' => 0],
                    'category' => ['hits' => 0, 'misses' => 0],
                    'shop' => ['hits' => 0, 'misses' => 0],
                    'store_api' => ['hits' => 0, 'misses' => 0],
                    'other' => ['hits' => 0, 'misses' => 0],
                    'homepage' => ['hits' => 0, 'misses' => 0],
                ],
                'generation_ms' => 0,
                'generation_count' => 0,
                'store_api_generation_ms' => 0,
                'store_api_generation_count' => 0
            ];
        
        try {
            if (class_exists('\Mamba\Support\CacheAdapter')) {
                // Read total hits and misses
                $accumulated['hits'] = (int)\Mamba\Support\CacheAdapter::get('accumulated_hits', 'mamba_stats') ?: 0;
                $accumulated['misses'] = (int)\Mamba\Support\CacheAdapter::get('accumulated_misses', 'mamba_stats') ?: 0;
                
                // Read type-specific stats
                foreach (array_keys($accumulated['by_type']) as $type) {
                    $accumulated['by_type'][$type]['hits'] = (int)\Mamba\Support\CacheAdapter::get("accumulated_{$type}_hits", 'mamba_stats') ?: 0;
                    $accumulated['by_type'][$type]['misses'] = (int)\Mamba\Support\CacheAdapter::get("accumulated_{$type}_misses", 'mamba_stats') ?: 0;
                }
                
                // Read generation stats
                $accumulated['generation_ms'] = (int)\Mamba\Support\CacheAdapter::get('accumulated_generation_ms', 'mamba_stats') ?: 0;
                $accumulated['generation_count'] = (int)\Mamba\Support\CacheAdapter::get('accumulated_generation_count', 'mamba_stats') ?: 0;
                
                // Read Store API generation stats
                $accumulated['store_api_generation_ms'] = (int)\Mamba\Support\CacheAdapter::get('accumulated_store_api_generation_ms', 'mamba_stats') ?: 0;
                $accumulated['store_api_generation_count'] = (int)\Mamba\Support\CacheAdapter::get('accumulated_store_api_generation_count', 'mamba_stats') ?: 0;
            }
        } catch (Exception $e) {
            // Fallback to file-based stats
            $accumulated = self::readFallbackStats();
        }
        
        return $accumulated;
    }
    
    /**
     * Read fallback stats from file
     */
    private static function readFallbackStats(): array {
        $fallbackFile = WP_CONTENT_DIR . '/cache/mamba/stats_fallback.json';
        $fallbackData = [];
        
        if (file_exists($fallbackFile)) {
            $fallbackData = json_decode(file_get_contents($fallbackFile), true) ?: [];
        }
        
        return [
            'hits' => (int)($fallbackData['hits'] ?? 0),
            'misses' => (int)($fallbackData['misses'] ?? 0),
            'by_type' => $fallbackData['by_type'] ?? [
                'product' => ['hits' => 0, 'misses' => 0],
                'category' => ['hits' => 0, 'misses' => 0],
                'shop' => ['hits' => 0, 'misses' => 0],
                'store_api' => ['hits' => 0, 'misses' => 0],
                'other' => ['hits' => 0, 'misses' => 0],
                'homepage' => ['hits' => 0, 'misses' => 0],
            ],
            'generation_ms' => (int)($fallbackData['generation_ms'] ?? 0),
            'generation_count' => (int)($fallbackData['generation_count'] ?? 0),
            'store_api_generation_ms' => (int)($fallbackData['store_api_generation_ms'] ?? 0),
            'store_api_generation_count' => (int)($fallbackData['store_api_generation_count'] ?? 0)
        ];
    }
    
    /**
     * Reset accumulated stats atomically
     */
    public static function resetAccumulatedStats(): void {
        try {
            if (class_exists('\Mamba\Support\CacheAdapter')) {
                // Delete all accumulated stats
                \Mamba\Support\CacheAdapter::delete('accumulated_hits', 'mamba_stats');
                \Mamba\Support\CacheAdapter::delete('accumulated_misses', 'mamba_stats');
                
                // Delete type-specific stats
                foreach (array_keys(self::$byType) as $type) {
                    \Mamba\Support\CacheAdapter::delete("accumulated_{$type}_hits", 'mamba_stats');
                    \Mamba\Support\CacheAdapter::delete("accumulated_{$type}_misses", 'mamba_stats');
                }
                
                // Delete generation stats
                \Mamba\Support\CacheAdapter::delete('accumulated_generation_ms', 'mamba_stats');
                \Mamba\Support\CacheAdapter::delete('accumulated_generation_count', 'mamba_stats');
                \Mamba\Support\CacheAdapter::delete('accumulated_store_api_generation_ms', 'mamba_stats');
                \Mamba\Support\CacheAdapter::delete('accumulated_store_api_generation_count', 'mamba_stats');
            }
            
            // Also clear fallback file
            $fallbackFile = WP_CONTENT_DIR . '/cache/mamba/stats_fallback.json';
            if (file_exists($fallbackFile)) {
                @unlink($fallbackFile);
            }
            
        } catch (Exception $e) {
            // Silently fail - reset failed
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Mamba: Failed to reset accumulated stats: ' . $e->getMessage());
            }
        }
    }
    
    /**
     * Read daily accumulated stats
     */
    private static function readDailyAccumulatedStats(): array {
        $today = wp_date('Y-m-d');
        $dailyStats = [
            'hits' => 0,
            'misses' => 0,
            'by_type' => [
                'product' => ['hits' => 0, 'misses' => 0],
                'category' => ['hits' => 0, 'misses' => 0],
                'shop' => ['hits' => 0, 'misses' => 0],
                'store_api' => ['hits' => 0, 'misses' => 0],
                'other' => ['hits' => 0, 'misses' => 0],
                'homepage' => ['hits' => 0, 'misses' => 0],
            ],
            'generation_ms' => 0,
            'generation_count' => 0
        ];
        
        try {
            if (class_exists('\Mamba\Support\CacheAdapter')) {
                // Read daily totals
                $dailyStats['hits'] = (int)\Mamba\Support\CacheAdapter::get("daily_{$today}_hits", 'mamba_stats') ?: 0;
                $dailyStats['misses'] = (int)\Mamba\Support\CacheAdapter::get("daily_{$today}_misses", 'mamba_stats') ?: 0;
                
                // Read daily type-specific stats
                foreach (array_keys($dailyStats['by_type']) as $type) {
                    $dailyStats['by_type'][$type]['hits'] = (int)\Mamba\Support\CacheAdapter::get("daily_{$today}_{$type}_hits", 'mamba_stats') ?: 0;
                    $dailyStats['by_type'][$type]['misses'] = (int)\Mamba\Support\CacheAdapter::get("daily_{$today}_{$type}_misses", 'mamba_stats') ?: 0;
                }
                
                // Read daily generation stats
                $dailyStats['generation_ms'] = (int)\Mamba\Support\CacheAdapter::get("daily_{$today}_generation_ms", 'mamba_stats') ?: 0;
                $dailyStats['generation_count'] = (int)\Mamba\Support\CacheAdapter::get("daily_{$today}_generation_count", 'mamba_stats') ?: 0;
            }
        } catch (Exception $e) {
            // Fallback to in-memory daily stats
            $dailyStats['hits'] = self::$dailyHits;
            $dailyStats['misses'] = self::$dailyMisses;
            $dailyStats['by_type'] = self::$dailyByType;
            $dailyStats['generation_ms'] = self::$dailyGenerationMs;
            $dailyStats['generation_count'] = self::$dailyGenerationCount;
        }
        
        return $dailyStats;
    }
    
    /**
     * Reset daily accumulated stats
     */
    public static function resetDailyAccumulatedStats(): void {
        try {
            if (class_exists('\Mamba\Support\CacheAdapter')) {
                $today = wp_date('Y-m-d');
                
                // Delete daily totals
                \Mamba\Support\CacheAdapter::delete("daily_{$today}_hits", 'mamba_stats');
                \Mamba\Support\CacheAdapter::delete("daily_{$today}_misses", 'mamba_stats');
                
                // Delete daily type-specific stats
                foreach (array_keys(self::$dailyByType) as $type) {
                    \Mamba\Support\CacheAdapter::delete("daily_{$today}_{$type}_hits", 'mamba_stats');
                    \Mamba\Support\CacheAdapter::delete("daily_{$today}_{$type}_misses", 'mamba_stats');
                }
                
                // Delete daily generation stats
                \Mamba\Support\CacheAdapter::delete("daily_{$today}_generation_ms", 'mamba_stats');
                \Mamba\Support\CacheAdapter::delete("daily_{$today}_generation_count", 'mamba_stats');
            }
        } catch (Exception $e) {
            // Silently fail - reset failed
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Mamba: Failed to reset daily accumulated stats: ' . $e->getMessage());
            }
        }
    }

    /**
     * Validate accumulated stats for data integrity
     */
    private static function validateAccumulatedStats(array $accumulated): array {
        // Ensure all values are non-negative
        $accumulated['hits'] = max(0, (int)($accumulated['hits'] ?? 0));
        $accumulated['misses'] = max(0, (int)($accumulated['misses'] ?? 0));
        $accumulated['generation_ms'] = max(0, (int)($accumulated['generation_ms'] ?? 0));
        $accumulated['generation_count'] = max(0, (int)($accumulated['generation_count'] ?? 0));
        $accumulated['store_api_generation_ms'] = max(0, (int)($accumulated['store_api_generation_ms'] ?? 0));
        $accumulated['store_api_generation_count'] = max(0, (int)($accumulated['store_api_generation_count'] ?? 0));
        
        // Validate by_type structure
        foreach ($accumulated['by_type'] as $type => &$counts) {
            $counts['hits'] = max(0, (int)($counts['hits'] ?? 0));
            $counts['misses'] = max(0, (int)($counts['misses'] ?? 0));
        }
        
        return $accumulated;
    }
    
    /**
     * Log stats operation for debugging
     */
    private static function logStatsOperation(string $operation, array $data = []): void {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            $logData = [
                'operation' => $operation,
                'timestamp' => time(),
                'data' => $data
            ];
            error_log('Mamba Stats: ' . json_encode($logData));
        }
    }
    
    /**
     * Emergency recovery method for corrupted stats
     */
    public static function emergencyRecovery(): void {
        try {
            // Reset all accumulated stats
            self::resetAccumulatedStats();
            self::resetDailyAccumulatedStats();
            
            // Clear fallback file
            $fallbackFile = WP_CONTENT_DIR . '/cache/mamba/stats_fallback.json';
            if (file_exists($fallbackFile)) {
                @unlink($fallbackFile);
            }
            
            // Log recovery
            self::logStatsOperation('emergency_recovery', ['status' => 'completed']);
            
        } catch (Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Mamba Stats: Emergency recovery failed: ' . $e->getMessage());
            }
        }
    }
}
