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

/**
 * Autoloader Class
 *
 * Dynamically loads classes based on the Kitsune_AI_Platform_ prefix.
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/includes
 */
class Kitsune_AI_Platform_Autoloader {

    /**
     * Register the autoloader
     */
    public static function register() {
        spl_autoload_register(array(__CLASS__, 'autoload'));
    }

    /**
     * Autoload callback
     *
     * @param string $class_name Configured class name
     */
    public static function autoload($class_name) {
        // Check if class starts with our prefix
        if (strpos($class_name, 'Kitsune_AI_Platform_') !== 0) {
            return;
        }

        // Remove prefix
        $relative_class = substr($class_name, 20); // Remove 'Kitsune_AI_Platform_'

        // Convert underscores to hyphens and lowercase
        $file_name = 'class-kitsune-ai-platform-' . str_replace('_', '-', strtolower($relative_class)) . '.php';

        // Interface file naming convention
        $interface_name = 'interface-kitsune-ai-platform-' . str_replace('_', '-', strtolower($relative_class)) . '.php';

        // Define potential paths
        $paths = array(
            KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/',
            KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/',
            KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/api/',
            KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/api/providers/',
            KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/automation/',
            KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/automation/triggers/',
            KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/automation/actions/',
            KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/vector-db/',
            KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/constants/',
            KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'admin/',
            KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'public/',
        );

        foreach ($paths as $path) {
            if (file_exists($path . $file_name)) {
                require_once $path . $file_name;
                return;
            }
            if (file_exists($path . $interface_name)) {
                require_once $path . $interface_name;
                return;
            }
        }
    }
}
