<?php

namespace FleekDash\Integrations\Core;

defined('ABSPATH') || exit;

/**
 * Integration System Bootstrap
 *
 * Initializes the new integration system
 */
class Bootstrap
{
    private static ?Bootstrap $instance = null;
    private Container $container;
    private bool $booted = false;

    private function __construct()
    {
        $this->container = Container::getInstance();
    }

    public static function getInstance(): Bootstrap
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Boot the integration system
     */
    public function boot(): void
    {
        if ($this->booted) {
            return;
        }

        // Check if migration is needed
        $migration = $this->container->make(MigrationManager::class);
        if ($this->needsMigration()) {
            $migration->migrate();
        }

        // Initialize core services
        $this->initializeCoreServices();

        // Register WordPress hooks
        $this->registerHooks();

        // Load active integrations
        $this->loadActiveIntegrations();

        $this->booted = true;

        // Fire booted event
        $this->container->getEvents()->dispatch('integrations.booted');
    }

    /**
     * Check if migration is needed
     */
    private function needsMigration(): bool
    {
        $currentVersion = get_option('fleekdash_integrations_version', '0.0.0');
        $systemVersion = '2.0.0';

        return version_compare($currentVersion, $systemVersion, '<');
    }

    /**
     * Initialize core services
     */
    private function initializeCoreServices(): void
    {
        // Initialize Discovery Engine
        $this->container->make(DiscoveryEngine::class);

        // Initialize Asset Manager
        $this->container->make(AssetManager::class);

        // Initialize Widget Manager
        $this->container->make(WidgetManager::class);

        // Initialize Settings Manager
        $this->container->make(SettingsManager::class);

        // Initialize Webhook Manager
        $webhookManager = $this->container->make(WebhookManager::class);
        $webhookManager->init();
    }

    /**
     * Register WordPress hooks
     */
    private function registerHooks(): void
    {
        add_action('init', [$this, 'init'], 0);
        add_action('rest_api_init', [$this, 'registerRestRoutes']);
        add_action('admin_menu', [$this, 'registerAdminMenu']);
        add_action('wp_ajax_fleekdash_integration_action', [$this, 'handleAjaxActions']);
    }

    /**
     * WordPress init hook
     */
    public function init(): void
    {
        // Initialize integrations that need early init
        $this->initializeEarlyIntegrations();
    }

    /**
     * Register REST API routes
     */
    public function registerRestRoutes(): void
    {
        register_rest_route('fleekdash/v1', '/integrations', [
            'methods' => 'GET',
            'callback' => [$this, 'getIntegrations'],
            'permission_callback' => [$this, 'checkPermissions']
        ]);

        register_rest_route('fleekdash/v1', '/integrations/(?P<id>[a-zA-Z0-9-_]+)', [
            'methods' => 'GET',
            'callback' => [$this, 'getIntegration'],
            'permission_callback' => [$this, 'checkPermissions']
        ]);

        register_rest_route('fleekdash/v1', '/integrations/(?P<id>[a-zA-Z0-9-_]+)/activate', [
            'methods' => 'POST',
            'callback' => [$this, 'activateIntegration'],
            'permission_callback' => [$this, 'checkPermissions']
        ]);

        register_rest_route('fleekdash/v1', '/integrations/(?P<id>[a-zA-Z0-9-_]+)/deactivate', [
            'methods' => 'POST',
            'callback' => [$this, 'deactivateIntegration'],
            'permission_callback' => [$this, 'checkPermissions']
        ]);
    }

    /**
     * Register admin menu
     */
    public function registerAdminMenu(): void
    {
        add_submenu_page(
            'fleekdash',
            'Integrations',
            'Integrations',
            'manage_options',
            'fleekdash-integrations',
            [$this, 'renderIntegrationsPage'],
        );
    }

    /**
     * Load active integrations
     */
    private function loadActiveIntegrations(): void
    {
        $discovery = $this->container->make(DiscoveryEngine::class);
        $activeIntegrations = get_option('fleekdash_active_integrations', []);
        $activeIntegrations = is_array($activeIntegrations) ? $activeIntegrations : [];

        foreach ($activeIntegrations as $integrationId) {
            if ($discovery->isAvailable($integrationId)) {
                $integration = $discovery->loadIntegration($integrationId);
                if ($integration) {
                    $this->activateIntegrationInstance($integration);
                }
            }
        }
    }

    /**
     * Initialize early integrations
     */
    private function initializeEarlyIntegrations(): void
    {
        // Load integrations that need to run early
        $earlyIntegrations = apply_filters('fleekdash_early_integrations', []);

        $discovery = $this->container->make(DiscoveryEngine::class);

        foreach ($earlyIntegrations as $integrationId) {
            if ($discovery->isAvailable($integrationId)) {
                $integration = $discovery->loadIntegration($integrationId);
                if ($integration) {
                    $this->activateIntegrationInstance($integration);
                }
            }
        }
    }

    /**
     * Activate integration instance
     */
    private function activateIntegrationInstance($integration): void
    {
        try {
            if (method_exists($integration, 'activate')) {
                $integration->activate();
            }

            // Get and register service provider if exists
            if (method_exists($integration, 'getServiceProvider')) {
                $providerClass = $integration->getServiceProvider();
                if (class_exists($providerClass)) {
                    $provider = new $providerClass($this->container);
                    $provider->register();
                    $provider->boot();
                }
            }
        } catch (\Exception $e) {
            error_log("Error activating integration: " . $e->getMessage());
        }
    }

    /**
     * REST API: Get all integrations
     */
    public function getIntegrations(): \WP_REST_Response
    {
        $discovery = $this->container->make(DiscoveryEngine::class);
        $integrations = $discovery->discover();
        $active = get_option('fleekdash_active_integrations', []);
        $active = is_array($active) ? $active : [];

        foreach ($integrations as &$integration) {
            $integration['active'] = in_array($integration['id'], $active);
            $integration['available'] = $discovery->isAvailable($integration['id']);
        }

        return rest_ensure_response($integrations);
    }

    /**
     * REST API: Get single integration
     */
    public function getIntegration(\WP_REST_Request $request): \WP_REST_Response
    {
        $id = $request->get_param('id');
        $discovery = $this->container->make(DiscoveryEngine::class);
        $integrations = $discovery->discover();

        if (!isset($integrations[$id])) {
            return rest_ensure_response(new \WP_Error('integration_not_found', 'Integration not found', ['status' => 404]));
        }

        $integration = $integrations[$id];
        $active = get_option('fleekdash_active_integrations', []);
        $active = is_array($active) ? $active : [];
        $integration['active'] = in_array($id, $active);
        $integration['available'] = $discovery->isAvailable($id);

        return rest_ensure_response($integration);
    }

    /**
     * REST API: Activate integration
     */
    public function activateIntegration(\WP_REST_Request $request): \WP_REST_Response
    {
        $id = $request->get_param('id');
        $discovery = $this->container->make(DiscoveryEngine::class);

        if (!$discovery->isAvailable($id)) {
            return rest_ensure_response(new \WP_Error('integration_not_available', 'Integration not available', ['status' => 400]));
        }

        $active = get_option('fleekdash_active_integrations', []);
        $active = is_array($active) ? $active : [];
        if (!in_array($id, $active)) {
            $active[] = $id;
            update_option('fleekdash_active_integrations', $active);
        }

        // Load and activate the integration
        $integration = $discovery->loadIntegration($id);
        if ($integration) {
            $this->activateIntegrationInstance($integration);
        }

        return rest_ensure_response(['success' => true]);
    }

    /**
     * REST API: Deactivate integration
     */
    public function deactivateIntegration(\WP_REST_Request $request): \WP_REST_Response
    {
        $id = $request->get_param('id');
        $active = get_option('fleekdash_active_integrations', []);
        $active = is_array($active) ? $active : [];

        $active = array_filter($active, function ($integrationId) use ($id) {
            return $integrationId !== $id;
        });

        update_option('fleekdash_active_integrations', array_values($active));

        return rest_ensure_response(['success' => true]);
    }

    /**
     * Check permissions for REST API
     */
    public function checkPermissions(): bool
    {
        return current_user_can('manage_options');
    }

    /**
     * Handle AJAX actions
     */
    public function handleAjaxActions(): void
    {
        check_ajax_referer('fleekdash_nonce');

        $action = sanitize_text_field($_POST['integration_action'] ?? '');
        $integration_id = sanitize_text_field($_POST['integration_id'] ?? '');

        switch ($action) {
            case 'generate':
                $this->handleGenerateIntegration();
                break;

            case 'rediscover':
                $this->handleRediscover();
                break;

            default:
                wp_die('Invalid action', 'Invalid Action', ['response' => 400]);
        }
    }

    /**
     * Handle generate integration
     */
    private function handleGenerateIntegration(): void
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
            return;
        }

        $params = [
            'id' => sanitize_text_field($_POST['id'] ?? ''),
            'name' => sanitize_text_field($_POST['name'] ?? ''),
            'description' => sanitize_textarea_field($_POST['description'] ?? ''),
            'category' => sanitize_text_field($_POST['category'] ?? 'plugin')
        ];

        try {
            $generator = new IntegrationGenerator();
            $result = $generator->generate($params);

            if ($result) {
                if (\function_exists('fleekdash_log_info')) {
                    \fleekdash_log_info(\sprintf(
                        'Integration generated: id=%s name=%s category=%s user_id=%d',
                        $params['id'],
                        $params['name'] ?? '',
                        $params['category'] ?? 'plugin',
                        \get_current_user_id()
                    ));
                }
                wp_send_json_success(['message' => 'Integration generated successfully']);
            } else {
                wp_send_json_error(['message' => 'Failed to generate integration']);
            }
        } catch (\Exception $e) {
            if (\function_exists('fleekdash_log_error')) {
                \fleekdash_log_error(\sprintf(
                    'Integration generation failed: id=%s user_id=%d error=%s',
                    $params['id'] ?? '',
                    \get_current_user_id(),
                    $e->getMessage()
                ));
            }
            wp_send_json_error(['message' => $e->getMessage()]);
        }
    }

    /**
     * Handle rediscover
     */
    private function handleRediscover(): void
    {
        $discovery = $this->container->make(DiscoveryEngine::class);
        $integrations = $discovery->rediscover();

        wp_send_json_success([
            'message' => 'Integrations rediscovered',
            'count' => count($integrations)
        ]);
    }

    /**
     * Render integrations admin page
     */
    public function renderIntegrationsPage(): void
    {
        // This would render the admin page - for now just a placeholder
        echo '<div id="fleekdash-integrations-app"></div>';

        // Enqueue React app for integrations management
        wp_enqueue_script('fleekdash-integrations-app');
    }

    /**
     * Get container instance
     */
    public function getContainer(): Container
    {
        return $this->container;
    }
}
