<?php
/**
 * ===========================================
 * FLOWBOT DCI - PSR-4 AUTOLOADER
 * ===========================================
 * Robust autoloader for the FlowbotDCI namespace
 */

// Store autoloader errors for debugging
$GLOBALS['autoload_errors'] = [];

spl_autoload_register(function ($class) {
    // Project namespace prefix
    $prefix = 'FlowbotDCI\\';

    // Base directory for the namespace
    $baseDir = __DIR__ . '/';

    // Check if the class uses the namespace prefix
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        // Not our namespace, skip
        return false;
    }

    // Get the relative class name
    $relativeClass = substr($class, $len);

    // Replace namespace separators with directory separators
    // Handle both Windows and Unix paths
    $file = $baseDir . str_replace('\\', DIRECTORY_SEPARATOR, $relativeClass) . '.php';

    // Normalize path
    $file = realpath($baseDir) . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $relativeClass) . '.php';

    // If realpath failed, use original path
    if (strpos($file, DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $relativeClass)) === false) {
        $file = $baseDir . str_replace('\\', DIRECTORY_SEPARATOR, $relativeClass) . '.php';
    }

    // Debug: Log attempted class loading
    if (defined('AUTOLOAD_DEBUG') && AUTOLOAD_DEBUG) {
        error_log("Autoloader: Attempting to load class '{$class}' from '{$file}'");
    }

    // If the file exists, require it
    if (file_exists($file)) {
        require $file;
        return true;
    }

    // Store error for debugging
    $GLOBALS['autoload_errors'][] = [
        'class' => $class,
        'file' => $file,
        'base_dir' => $baseDir,
        'relative_class' => $relativeClass
    ];

    // Log error
    error_log("Autoloader: Failed to find class '{$class}' at '{$file}'");

    return false;
});

/**
 * Helper function to get autoloader errors
 */
function getAutoloadErrors(): array
{
    return $GLOBALS['autoload_errors'] ?? [];
}

/**
 * Helper function to verify all core classes can be loaded
 */
function verifyAutoloader(): array
{
    $coreClasses = [
        'FlowbotDCI\\Core\\Application',
        'FlowbotDCI\\Core\\Database',
        'FlowbotDCI\\Core\\ConnectionPool',      // v3.0 - Connection pooling
        'FlowbotDCI\\Services\\WebScraper',
        'FlowbotDCI\\Services\\MetadataExtractor',
        'FlowbotDCI\\Services\\ProgressTracker',
        'FlowbotDCI\\Services\\EmbedGenerator',
        'FlowbotDCI\\Services\\UrlProcessor',
        'FlowbotDCI\\Services\\RedisService',    // v3.0 - Redis caching
        'FlowbotDCI\\Models\\PinFeed',
        'FlowbotDCI\\Models\\FeedData',
        'FlowbotDCI\\Models\\User',
        'FlowbotDCI\\Utils\\AuthorGenerator',
        'FlowbotDCI\\Utils\\TagExtractor',
    ];

    $results = [];
    $baseDir = __DIR__ . DIRECTORY_SEPARATOR;

    foreach ($coreClasses as $class) {
        $relativeClass = substr($class, strlen('FlowbotDCI\\'));
        $file = $baseDir . str_replace('\\', DIRECTORY_SEPARATOR, $relativeClass) . '.php';

        $results[$class] = [
            'file' => $file,
            'exists' => file_exists($file),
            'readable' => is_readable($file)
        ];
    }

    return $results;
}
