<?php

namespace GriffinForms\Includes\Integrations\XAi;

/**
 * xAI Integration
 *
 * Manages BYO API key configuration for Griffin Assist AI features via Grok.
 * Global-only integration; no per-form configuration surface.
 *
 * @since 3.1.3.0
 */
class Main extends \GriffinForms\Includes\Integrations\Format
{
    protected function setMeta()
    {
        $this->meta = 'xai';
        $this->id   = 'xai';
    }

    protected function buildInfo(): array
    {
        return [
            'id'          => 'xai',
            'name'        => 'xAI',
            'category'    => 'AI',
            'description' => __('Connect your xAI API key to power Griffin Assist features with Grok models.', 'griffinforms-form-builder'),
            'scope'       => [
                'is_global'      => true,
                'allow_override' => false,
            ],
            'coming_soon' => false,
        ];
    }

    public function getStatus(): array
    {
        $configured = $this->isConfigured();

        return [
            'configured' => $configured,
            'active'     => $configured,
            'message'    => $configured
                ? __('Connected', 'griffinforms-form-builder')
                : __('API key required', 'griffinforms-form-builder'),
        ];
    }

    public function getConfigFields(): array
    {
        return [];
    }

    /** @var string|null */
    private $decrypted_api_key = null;

    private function getApiKey(): string
    {
        if ($this->decrypted_api_key === null) {
            wp_cache_delete('gf_assist_xai_key', 'griffinforms-form-builder');
            $this->decrypted_api_key = trim((string) $this->settings->getOption('gf_assist_xai_key'));
        }

        return $this->decrypted_api_key;
    }

    public function isConfigured(): bool
    {
        return !empty($this->getApiKey());
    }

    protected function saveConfiguration(array $config): bool
    {
        try {
            $api_key = isset($config['gf_assist_xai_key'])
                ? sanitize_text_field($config['gf_assist_xai_key'])
                : '';

            $model = isset($config['gf_assist_xai_model'])
                ? sanitize_text_field($config['gf_assist_xai_model'])
                : 'grok-3-mini';

            $allowed_models = array_keys($this->getSupportedModels());
            if (!in_array($model, $allowed_models, true)) {
                $model = 'grok-3-mini';
            }

            $this->settings->updateOption('gf_assist_xai_key', $api_key, 'ai');
            $this->settings->updateOption('gf_assist_xai_model', $model, 'ai');

            return true;
        } catch (\Exception $e) {
            $this->log->add(
                'error',
                'integration',
                0,
                get_current_user_id(),
                'Failed to save xAI configuration: ' . $e->getMessage(),
                'integration (xai)'
            );
            return false;
        }
    }

    protected function validateConnection(): array
    {
        $api_key = $this->getApiKey();

        if (empty($api_key)) {
            return [
                'success' => false,
                'message' => __('No API key is saved. Please enter your key and save first.', 'griffinforms-form-builder'),
            ];
        }

        $response = wp_remote_get('https://api.x.ai/v1/models', [
            'headers' => [
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type'  => 'application/json',
            ],
            'timeout' => 15,
        ]);

        if (is_wp_error($response)) {
            $message = 'xAI connection test failed (network error): ' . $response->get_error_message();
            $this->log->add('error', 'integration', 0, get_current_user_id(), $message, 'integration (xai)');
            return [
                'success' => false,
                'message' => $response->get_error_message(),
            ];
        }

        $code = (int) wp_remote_retrieve_response_code($response);

        if ($code === 200) {
            $message = 'xAI connection test successful (HTTP 200).';
            $this->log->add('success', 'integration', 0, get_current_user_id(), $message, 'integration (xai)');
            return [
                'success' => true,
                'message' => __('Connection verified successfully.', 'griffinforms-form-builder'),
            ];
        }

        $body_str = wp_remote_retrieve_body($response);
        $message  = 'xAI connection test failed: HTTP ' . $code . ' — ' . $body_str;
        $this->log->add('error', 'integration', 0, get_current_user_id(), $message, 'integration (xai)');

        return [
            'success' => false,
            'message' => sprintf(
                /* translators: %d: HTTP response code */
                __('xAI returned HTTP %d. Please check your API key.', 'griffinforms-form-builder'),
                $code
            ),
        ];
    }

    public function isLibraryInstalled(): bool
    {
        return true;
    }

    public function getLibraryInstructions(): string
    {
        return '';
    }

    protected function getSupportedModels(): array
    {
        return [
            'grok-3-mini' => 'Grok 3 Mini (Recommended)',
            'grok-3'      => 'Grok 3',
            'grok-2'      => 'Grok 2',
        ];
    }

    public function getConfigurationFormHtml(): string
    {
        $api_key     = $this->settings->getOption('gf_assist_xai_key', '');
        $saved_model = $this->settings->getOption('gf_assist_xai_model', 'grok-3-mini');

        $factory = new \GriffinForms\Includes\Integrations\FormControls\Factory();

        $fields_html = '';

        $fields_html .= $factory->create(
            'password',
            'gf_assist_xai_key',
            $api_key,
            'xai',
            [
                'label'       => __('API Key', 'griffinforms-form-builder'),
                'type'        => 'password',
                'required'    => true,
                'description' => __('Your API key from console.x.ai. It is encrypted before storage.', 'griffinforms-form-builder'),
            ]
        )->render();

        $fields_html .= $factory->create(
            'select',
            'gf_assist_xai_model',
            $saved_model,
            'xai',
            [
                'label'       => __('Default Model', 'griffinforms-form-builder'),
                'required'    => false,
                'options'     => $this->getSupportedModels(),
                'description' => __('The Grok model used for all Griffin Assist features unless overridden.', 'griffinforms-form-builder'),
            ]
        )->render();

        return $this->renderConfigurationFormTemplate('gf-xai-config-form', 'xai', $fields_html);
    }

    public function getConfigurationJs(): string
    {
        return "
        (function() {
            const form = document.getElementById('gf-xai-config-form');
            if (!form) return;

            const cancelBtn = form.querySelector('.gf-integration-btn-cancel');
            if (cancelBtn) {
                cancelBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    window.loadIntegrationInfo('xai');
                });
            }

            form.addEventListener('submit', function(e) {
                e.preventDefault();

                const keyField   = form.querySelector('#gf-xai-gf_assist_xai_key');
                const modelField = form.querySelector('#gf-xai-gf_assist_xai_model');

                if (!keyField || !keyField.value.trim()) {
                    window.showIntegrationsMessage('danger', 'Please enter your xAI API key.');
                    return;
                }

                const data = {
                    action: 'saveIntegrationConfiguration',
                    integration_id: 'xai',
                    nonce: window.griffinformsIntegrationsNonce || '',
                    gf_assist_xai_key: keyField.value.trim(),
                    gf_assist_xai_model: modelField ? modelField.value : 'grok-3-mini',
                };

                jQuery.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: data,
                    success: function(response) {
                        if (response.success) {
                            window.showIntegrationsMessage('success', 'xAI configuration saved.');
                            setTimeout(() => window.loadIntegrationInfo('xai'), 1000);
                        } else {
                            const msg = (response.data && response.data.msg) ? response.data.msg : 'Failed to save configuration.';
                            window.showIntegrationsMessage('danger', msg);
                        }
                    },
                    error: function() {
                        window.showIntegrationsMessage('danger', 'Error saving xAI configuration.');
                    }
                });
            });
        })();
        ";
    }
}
