<?php
/**
 * LLM Settings Controller V1
 *
 * @package ZenoChatbot\Http\Controller\Api\V1
 */

namespace ZenoChatbot\Http\Controller\Api\V1;

use ZenoChatbot\Framework\Support\Arr;
use ZenoChatbot\Framework\Validation\ValidationException;
use ZenoChatbot\Helper\LLMHelper;
use ZenoChatbot\Helper\Security;
use ZenoChatbot\Helper\Settings;
use ZenoChatbot\App;
use ZenoChatbot\Services\LLMService\LLMService;
use ZenoChatbot\Framework\Http\Request;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * LLM Settings API Controller
 *
 * Handles LLM-specific settings operations, merging static config
 * with dynamic user settings and ensuring API key security.
 */
class LLMSettingsController
{
    /**
     * Get LLM settings
     *
     * Merges static config from config/api.php with user settings,
     * but never exposes actual API keys in the response.
     *
     * @return array
     */
    public function get()
    {
        // Get defaults and provider configs from api.php
        $defaults = LLMHelper::getDefaultLLMProvider();
        $providers = LLMHelper::getAvailableProviders();
        $llmSettings = Settings::getLLMSettings();

        $isConfigured = Arr::has($llmSettings, 'api_key') && !empty(Arr::get($llmSettings, 'api_key'));

        // Get current provider (or default if not configured)
        $currentProvider = Arr::get($llmSettings, 'provider', $defaults['provider'] ?? 'openai');
        $currentProviderConfig = $providers[$currentProvider] ?? null;

        $currentModel = Arr::get($llmSettings, 'model', $defaults['model'] ?? 'gpt-3.5-turbo');
        $temperature = Arr::get($llmSettings, 'temperature', $defaults['temperature'] ?? 0.7);
        $maxTokens = Arr::get($llmSettings, 'max_tokens', $defaults['max_tokens'] ?? 1000);
        $maskedApiKey = $isConfigured ? '••••••••••••••••' : '';

        $settings = [
            // Configuration status
            'is_configured'           => $isConfigured,

            // Current active configuration
            'provider'                => $currentProvider,
            'model'                   => $currentModel,
            'temperature'             => $temperature,
            'max_tokens'              => $maxTokens,
            'has_api_key'             => $isConfigured,
            'api_key'                 => $maskedApiKey,

            // Available options
            'available_providers'     => $providers,
            'current_provider_config' => $currentProviderConfig,

            // Validation limits
            'limits'                  => App::config('api.llm_limits', []),
        ];

        return [
            'success' => true,
            'data'    => $settings
        ];
    }

    /**
     * Update LLM settings
     *
     * @param Request $request
     * @return array
     * @throws ValidationException
     */
    public function update(Request $request)
    {
        // Get available providers for validation
        $providers = App::config('api.llm_providers', []);

        $availableModels = array_map(function ($config) {
            return array_keys($config['models'] ?? []);
        }, $providers);

        $request->validate([
            'provider'    => 'required|in:' . implode(',', array_keys($providers)),
            'model'       => 'required|string|in:' . implode(',', $availableModels[$request->get('provider') ?? '']),
            'temperature' => 'numeric|min:0|max:2',
            'max_tokens'  => 'numeric|min:50',
            'api_key'     => 'nullable|string|min:15'
        ]);

        $dataToStore = [
            'provider'    => $request->getSafe('provider', 'sanitize_text_field'),
            'model'       => $request->getSafe('model', 'sanitize_text_field'),
            'temperature' => $request->getSafe('temperature', 'floatval'),
            'max_tokens'  => $request->getSafe('max_tokens', 'intval'),
            'api_key'     => $request->getSafe('api_key', 'sanitize_text_field'),
        ];

        $settings = Settings::updateLLMSettings($dataToStore);

        return [
            'data'    => $settings,
            'message' => 'LLM settings updated successfully'
        ];
    }

    /**
     * Test LLM connection
     *
     * @param \WP_REST_Request $request
     * @return array
     */
    public function testConnection(\WP_REST_Request $request)
    {
        try {
            $llmService = LLMService::create();
            $result = $llmService->testConnection();

            return [
                'success'  => $result['success'],
                'message'  => $result['message'],
                'provider' => $result['provider'] ?? null
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Connection test failed',
                'error'   => $e->getMessage(),
                'status'  => 500
            ];
        }
    }
}
