<?php

namespace GriffinForms\Includes\Integrations\Mistral;

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

    protected function buildInfo(): array
    {
        return [
            'id'          => 'mistral',
            'name'        => 'Mistral AI',
            'category'    => 'AI',
            'description' => __('Connect your Mistral API key to power Griffin Assist features with Mistral 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_mistral_key', 'griffinforms-form-builder');
            $this->decrypted_api_key = trim((string) $this->settings->getOption('gf_assist_mistral_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_mistral_key'])
                ? sanitize_text_field($config['gf_assist_mistral_key'])
                : '';

            $model = isset($config['gf_assist_mistral_model'])
                ? sanitize_text_field($config['gf_assist_mistral_model'])
                : 'mistral-small-latest';

            $allowed_models = array_keys($this->getSupportedModels());
            if (!in_array($model, $allowed_models, true)) {
                $model = 'mistral-small-latest';
            }

            $this->settings->updateOption('gf_assist_mistral_key', $api_key, 'ai');
            $this->settings->updateOption('gf_assist_mistral_model', $model, 'ai');

            return true;
        } catch (\Exception $e) {
            $this->log->add(
                'error',
                'integration',
                0,
                get_current_user_id(),
                'Failed to save Mistral configuration: ' . $e->getMessage(),
                'integration (mistral)'
            );
            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.mistral.ai/v1/models', [
            'headers' => [
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type'  => 'application/json',
            ],
            'timeout' => 15,
        ]);

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

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

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

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

        return [
            'success' => false,
            'message' => sprintf(
                /* translators: %d: HTTP response code */
                __('Mistral 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 [
            'mistral-small-latest'  => 'Mistral Small (Recommended)',
            'mistral-medium-latest' => 'Mistral Medium',
            'mistral-large-latest'  => 'Mistral Large',
        ];
    }

    public function getConfigurationFormHtml(): string
    {
        $api_key     = $this->settings->getOption('gf_assist_mistral_key', '');
        $saved_model = $this->settings->getOption('gf_assist_mistral_model', 'mistral-small-latest');

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

        $fields_html = '';

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

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

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

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

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

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

                const keyField   = form.querySelector('#gf-mistral-gf_assist_mistral_key');
                const modelField = form.querySelector('#gf-mistral-gf_assist_mistral_model');

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

                const data = {
                    action: 'saveIntegrationConfiguration',
                    integration_id: 'mistral',
                    nonce: window.griffinformsIntegrationsNonce || '',
                    gf_assist_mistral_key: keyField.value.trim(),
                    gf_assist_mistral_model: modelField ? modelField.value : 'mistral-small-latest',
                };

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