<?php
/**
 * Warmup Error Tracker Service
 *
 * Tracks and manages cache warmup errors for debugging and monitoring,
 * with automatic cleanup to prevent storage bloat.
 *
 * @package Mamba\Modules\Caching\Services\Preload\Warmup
 * @since   1.0.0
 */

namespace Mamba\Modules\Caching\Services\Preload\Warmup;

/**
 * Class ErrorTracker
 *
 * Tracks warmup errors with detailed information including URL,
 * error type, status code, response time, and device variant.
 *
 * @since 1.0.0
 */
final class ErrorTracker {
    
    /**
     * Track a warmup error with detailed information
     */
    public static function trackError(string $url, string $errorType, array $details = []): void {
        $error = [
            'url' => $url,
            'error_type' => $errorType,
            'error_message' => $details['message'] ?? '',
            'status_code' => $details['status_code'] ?? 0,
            'response_time' => $details['response_time'] ?? 0,
            'timestamp' => time(),
            'device_variant' => $details['device'] ?? 'unknown',
            'attempt' => $details['attempt'] ?? 1,
            'curl_error' => $details['curl_error'] ?? '',
            'headers' => $details['headers'] ?? []
        ];
        
        // Store error in WordPress options
        $errors = get_option('mamba_warmup_errors', []);
        $errors[] = $error;
        
        // Keep only last 100 errors to prevent storage bloat
        if (count($errors) > 100) {
            $errors = array_slice($errors, -100);
        }
        
        update_option('mamba_warmup_errors', $errors);
    }
    
    /**
     * Get all tracked errors
     */
    public static function getErrors(): array {
        return get_option('mamba_warmup_errors', []);
    }
    
    /**
     * Get errors for a specific job
     */
    public static function getJobErrors(string $jobId): array {
        $allErrors = self::getErrors();
        return array_filter($allErrors, function($error) use ($jobId) {
            return isset($error['job_id']) && $error['job_id'] === $jobId;
        });
    }
    
    /**
     * Clear old errors (older than 24 hours)
     */
    public static function clearOldErrors(): void {
        $errors = self::getErrors();
        $cutoff = time() - (24 * 60 * 60); // 24 hours ago
        
        $errors = array_filter($errors, function($error) use ($cutoff) {
            return ($error['timestamp'] ?? 0) > $cutoff;
        });
        
        update_option('mamba_warmup_errors', array_values($errors));
    }
    
    /**
     * Get error statistics
     */
    public static function getErrorStats(): array {
        $errors = self::getErrors();
        $stats = [
            'total_errors' => count($errors),
            'error_types' => [],
            'status_codes' => [],
            'recent_errors' => array_slice($errors, -10) // Last 10 errors
        ];
        
        foreach ($errors as $error) {
            $errorType = $error['error_type'] ?? 'unknown';
            $statusCode = $error['status_code'] ?? 0;
            
            $stats['error_types'][$errorType] = ($stats['error_types'][$errorType] ?? 0) + 1;
            if ($statusCode > 0) {
                $stats['status_codes'][$statusCode] = ($stats['status_codes'][$statusCode] ?? 0) + 1;
            }
        }
        
        return $stats;
    }
    
    /**
     * Group errors by type for better reporting
     */
    public static function groupErrorsByType(): array {
        $errors = self::getErrors();
        $grouped = [];
        
        foreach ($errors as $error) {
            $type = $error['error_type'] ?? 'unknown';
            if (!isset($grouped[$type])) {
                $grouped[$type] = [];
            }
            $grouped[$type][] = $error;
        }
        
        return $grouped;
    }
}
