<?php

namespace FleekDash\Core;

defined('ABSPATH') || exit;

/**
 * Emergency fallback loader for active integrations.
 * Ensures integrations load even if integrations/integrations.php fails.
 */
class IntegrationLoader
{
    public static function loadActiveIntegrations(): void
    {
        $active = get_option('fleekdash_active_integrations', []);

        if (empty($active)) {
            return;
        }

        foreach ($active as $integrations) {
            if (!is_array($integrations)) {
                continue;
            }

            foreach ($integrations as $integration_id) {
                self::loadIntegrationIfNeeded($integration_id);
            }
        }
    }

    private static function loadIntegrationIfNeeded(string $integration_id): void
    {
        // Skip legacy OpenAI (includes/AI/ v2.3) and already-loaded integrations
        $skipLegacyOpenai = ($integration_id === 'openai');
        $alreadyLoaded = did_action("fleekdash_integration_loaded_{$integration_id}");
        if ($skipLegacyOpenai || $alreadyLoaded) {
            return;
        }

        try {
            $integration_path = FLEEKDASH_PLUGIN_DIR . 'integrations/' . $integration_id;
            $integration_file = $integration_path . '/Integration.php';

            if (!file_exists($integration_file)) {
                return;
            }

            self::loadIntegrationDependencies($integration_id, $integration_path);
            require_once $integration_file;

            $class_name = self::resolveIntegrationClass($integration_id, $integration_file);
            if ($class_name === null || !class_exists($class_name)) {
                return;
            }

            self::initializeAndRegisterIntegration($class_name, $integration_path, $integration_id);
        } catch (\Exception $e) {
            // Silent fail - don't break site
        }
    }

    private static function loadIntegrationDependencies(string $integration_id, string $integration_path): void
    {
        if ($integration_id !== 'openai') {
            return;
        }

        require_once $integration_path . '/OpenAIClient.php';
        require_once $integration_path . '/streams/OpenAIStream.php';
        require_once $integration_path . '/prompts/WordPress.php';
        require_once $integration_path . '/tools/WordPress.php';
    }

    private static function resolveIntegrationClass(string $integration_id, string $integration_file): ?string
    {
        $content = file_get_contents($integration_file);
        if (preg_match('/namespace\s+([^;]+);/', $content, $matches)) {
            $namespace = trim($matches[1]);
            $parts = explode('\\', $namespace);
            $namespace_part = end($parts);

            return 'FleekDash\\Integrations\\' . $namespace_part . '\\Integration';
        }

        return 'FleekDash\\Integrations\\' . ucfirst($integration_id) . '\\Integration';
    }

    private static function initializeAndRegisterIntegration(
        string $class_name,
        string $integration_path,
        string $integration_id
    ): void {
        $integration = new $class_name($integration_path);
        $integration->init();
        $integration->registerHooks();

        if (did_action('rest_api_init')) {
            $integration->registerRestRoutes();
        } else {
            add_action('rest_api_init', function () use ($integration) {
                $integration->registerRestRoutes();
            });
        }

        do_action("fleekdash_integration_loaded_{$integration_id}", $integration);
    }
}
