<?php

namespace GriffinForms\Includes\Integrations\Anthropic;

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

    /**
     * Build integration metadata.
     *
     * @return array
     */
    protected function buildInfo(): array
    {
        return [
            'id'          => 'anthropic',
            'name'        => 'Anthropic',
            'category'    => 'AI',
            'description' => __('Connect your Anthropic API key to power Griffin Assist features with Claude.', 'griffinforms-form-builder'),
            'scope'       => [
                'is_global'      => true,
                'allow_override' => false,
            ],
            'coming_soon' => false,
        ];
    }

    /**
     * Current integration status.
     *
     * @return array
     */
    public function getStatus(): array
    {
        $configured = $this->isConfigured();

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

    /**
     * No field schema used (HTML-driven configure view).
     *
     * @return array
     */
    public function getConfigFields(): array
    {
        return [];
    }

    /**
     * Per-instance cache for the decrypted API key.
     *
     * @var string|null  null = not yet read, '' = confirmed empty
     */
    private $decrypted_api_key = null;

    /**
     * Read and cache the decrypted API key for this request.
     *
     * @return string
     */
    private function getApiKey(): string
    {
        if ($this->decrypted_api_key === null) {
            wp_cache_delete('gf_assist_anthropic_key', 'griffinforms-form-builder');
            $own_key = trim((string) $this->settings->getOption('gf_assist_anthropic_key'));
            $this->decrypted_api_key = $own_key !== '' ? $own_key : $this->resolveConnectorApiKey('anthropic');
        }

        return $this->decrypted_api_key;
    }

    /**
     * Check if the integration is configured.
     *
     * @return bool
     */
    public function isConfigured(): bool
    {
        return !empty($this->getApiKey());
    }

    /**
     * Save configuration — persists the API key and model preference.
     *
     * @param array $config
     * @return bool
     */
    protected function saveConfiguration(array $config): bool
    {
        try {
            $api_key = isset($config['gf_assist_anthropic_key'])
                ? sanitize_text_field($config['gf_assist_anthropic_key'])
                : '';

            $model = isset($config['gf_assist_anthropic_model'])
                ? sanitize_text_field($config['gf_assist_anthropic_model'])
                : 'claude-haiku-4-5';

            $allowed_models = array_keys($this->getSupportedModels());
            if (!in_array($model, $allowed_models, true)) {
                $model = 'claude-haiku-4-5';
            }

            $this->settings->updateOption('gf_assist_anthropic_key', $api_key, 'ai');
            $this->settings->updateOption('gf_assist_anthropic_model', $model, 'ai');

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

    /**
     * Validate connection with a minimal 1-token request.
     *
     * @return array
     */
    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'),
            ];
        }

        $body = [
            'model'      => 'claude-haiku-4-5',
            'max_tokens' => 1,
            'messages'   => [
                ['role' => 'user', 'content' => 'hi'],
            ],
        ];

        $response = wp_remote_post('https://api.anthropic.com/v1/messages', [
            'headers' => [
                'x-api-key'         => $api_key,
                'anthropic-version' => '2023-06-01',
                'Content-Type'      => 'application/json',
            ],
            'body'    => wp_json_encode($body),
            'timeout' => 15,
        ]);

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

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

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

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

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

    /**
     * No external library required.
     *
     * @return bool
     */
    public function isLibraryInstalled(): bool
    {
        return true;
    }

    /**
     * No library instructions required.
     *
     * @return string
     */
    public function getLibraryInstructions(): string
    {
        return '';
    }

    /**
     * Supported Claude model options.
     *
     * @return array slug => label
     */
    protected function getSupportedModels(): array
    {
        return [
            'claude-haiku-4-5'  => 'Claude Haiku 4.5 (Recommended)',
            'claude-sonnet-4-6' => 'Claude Sonnet 4.6',
            'claude-opus-4-7'   => 'Claude Opus 4.7',
        ];
    }

    /**
     * Render the configuration form HTML for the integrations modal.
     *
     * @return string
     */
    public function getConfigurationFormHtml(): string
    {
        $api_key     = $this->settings->getOption('gf_assist_anthropic_key', '');
        $saved_model = $this->settings->getOption('gf_assist_anthropic_model', 'claude-haiku-4-5');

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

        $fields_html = '';

        $connector_key = trim($api_key) === '' ? $this->resolveConnectorApiKey('anthropic') : '';
        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_anthropic_key',
            $api_key,
            'anthropic',
            [
                'label'       => __('API Key', 'griffinforms-form-builder'),
                'type'        => 'password',
                'required'    => $connector_key === '',
                'description' => __('Your secret key from console.anthropic.com. It is encrypted before storage.', 'griffinforms-form-builder'),
            ]
        )->render();

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

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

    /**
     * JavaScript handler for the configuration form.
     *
     * @return string
     */
    public function getConfigurationJs(): string
    {
        return "
        (function() {
            const form = document.getElementById('gf-anthropic-config-form');
            if (!form) return;

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

            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: 'anthropic',
                            nonce: window.griffinformsIntegrationsNonce || '',
                            gf_assist_anthropic_key: '',
                            gf_assist_anthropic_model: 'claude-haiku-4-5',
                        },
                        success: function(response) {
                            if (response.success) {
                                window.showIntegrationsMessage('success', 'Anthropic key removed.');
                                setTimeout(() => window.loadIntegrationInfo('anthropic'), 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 Anthropic key.');
                        }
                    });
                });
            }

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

                const keyField   = form.querySelector('#gf-anthropic-gf_assist_anthropic_key');
                const modelField = form.querySelector('#gf-anthropic-gf_assist_anthropic_model');

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

                const data = {
                    action: 'saveIntegrationConfiguration',
                    integration_id: 'anthropic',
                    nonce: window.griffinformsIntegrationsNonce || '',
                    gf_assist_anthropic_key: keyField.value.trim(),
                    gf_assist_anthropic_model: modelField ? modelField.value : 'claude-haiku-4-5',
                };

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