<?php

namespace GriffinForms\Includes\Integrations\Gemini;

/**
 * Google Gemini Integration
 *
 * Manages BYO API key configuration for Griffin Assist AI features via Gemini.
 * 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 = 'gemini';
        $this->id   = 'gemini';
    }

    protected function buildInfo(): array
    {
        return [
            'id'          => 'gemini',
            'name'        => 'Google Gemini',
            'category'    => 'AI',
            'description' => __('Connect your Google AI API key to power Griffin Assist features with Gemini 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 [];
    }

    /**
     * Per-instance cache for the decrypted API key.
     *
     * @var string|null
     */
    private $decrypted_api_key = null;

    private function getApiKey(): string
    {
        if ($this->decrypted_api_key === null) {
            wp_cache_delete('gf_assist_gemini_key', 'griffinforms-form-builder');
            $own_key = trim((string) $this->settings->getOption('gf_assist_gemini_key'));
            $this->decrypted_api_key = $own_key !== '' ? $own_key : $this->resolveConnectorApiKey('google');
        }

        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_gemini_key'])
                ? sanitize_text_field($config['gf_assist_gemini_key'])
                : '';

            $model = isset($config['gf_assist_gemini_model'])
                ? sanitize_text_field($config['gf_assist_gemini_model'])
                : 'gemini-2.0-flash';

            $allowed_models = array_keys($this->getSupportedModels());
            if (!in_array($model, $allowed_models, true)) {
                $model = 'gemini-2.0-flash';
            }

            $this->settings->updateOption('gf_assist_gemini_key', $api_key, 'ai');
            $this->settings->updateOption('gf_assist_gemini_model', $model, 'ai');

            return true;
        } catch (\Exception $e) {
            $this->log->add(
                'error',
                'integration',
                0,
                get_current_user_id(),
                'Failed to save Gemini configuration: ' . $e->getMessage(),
                'integration (gemini)'
            );
            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://generativelanguage.googleapis.com/v1beta/models?key=' . rawurlencode($api_key),
            ['timeout' => 15]
        );

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

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

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

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

        return [
            'success' => false,
            'message' => sprintf(
                /* translators: %d: HTTP response code */
                __('Google Gemini 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 [
            'gemini-2.0-flash'      => 'Gemini 2.0 Flash (Recommended)',
            'gemini-2.0-flash-lite' => 'Gemini 2.0 Flash Lite',
            'gemini-1.5-pro'        => 'Gemini 1.5 Pro',
        ];
    }

    public function getConfigurationFormHtml(): string
    {
        $api_key     = $this->settings->getOption('gf_assist_gemini_key', '');
        $saved_model = $this->settings->getOption('gf_assist_gemini_model', 'gemini-2.0-flash');

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

        $fields_html = '';

        $connector_key = trim($api_key) === '' ? $this->resolveConnectorApiKey('google') : '';
        if ($connector_key !== '') {
            $fields_html .= '<div class="gf-notice gf-notice-info mb-3">' .
                wp_kses_post(__('Using API key from <strong>WordPress Settings → Connectors</strong>. Enter a key below to override it for GriffinForms specifically.', 'griffinforms-form-builder')) .
                '</div>';
        }

        $fields_html .= $factory->create(
            'password',
            'gf_assist_gemini_key',
            $api_key,
            'gemini',
            [
                'label'       => __('API Key', 'griffinforms-form-builder'),
                'type'        => 'password',
                'required'    => $connector_key === '',
                'description' => __('Your API key from aistudio.google.com. It is encrypted before storage.', 'griffinforms-form-builder'),
            ]
        )->render();

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

        return $this->renderConfigurationFormTemplate('gf-gemini-config-form', 'gemini', $fields_html, [
            'show_remove' => trim($api_key) !== '',
        ]);
    }

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

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

            const removeBtn = form.querySelector('.gf-integration-btn-remove');
            if (removeBtn) {
                removeBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    jQuery.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'saveIntegrationConfiguration',
                            integration_id: 'gemini',
                            nonce: window.griffinformsIntegrationsNonce || '',
                            gf_assist_gemini_key: '',
                            gf_assist_gemini_model: 'gemini-2.0-flash',
                        },
                        success: function(response) {
                            if (response.success) {
                                window.showIntegrationsMessage('success', 'Gemini key removed.');
                                setTimeout(() => window.loadIntegrationInfo('gemini'), 1000);
                            } else {
                                const msg = (response.data && response.data.msg) ? response.data.msg : 'Failed to remove key.';
                                window.showIntegrationsMessage('danger', msg);
                            }
                        },
                        error: function() {
                            window.showIntegrationsMessage('danger', 'Error removing Gemini key.');
                        }
                    });
                });
            }

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

                const keyField   = form.querySelector('#gf-gemini-gf_assist_gemini_key');
                const modelField = form.querySelector('#gf-gemini-gf_assist_gemini_model');

                if (keyField && keyField.required && !keyField.value.trim()) {
                    window.showIntegrationsMessage('danger', 'Please enter your Google Gemini API key.');
                    return;
                }

                const data = {
                    action: 'saveIntegrationConfiguration',
                    integration_id: 'gemini',
                    nonce: window.griffinformsIntegrationsNonce || '',
                    gf_assist_gemini_key: keyField.value.trim(),
                    gf_assist_gemini_model: modelField ? modelField.value : 'gemini-2.0-flash',
                };

                jQuery.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: data,
                    success: function(response) {
                        if (response.success) {
                            window.showIntegrationsMessage('success', 'Gemini configuration saved.');
                            setTimeout(() => window.loadIntegrationInfo('gemini'), 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 Gemini configuration.');
                    }
                });
            });
        })();
        ";
    }
}
