<?php
// Service/Features/ApiClientService.php
// 该文件负责处理与 AI API 客户端相关的逻辑，例如客户端的创建。

namespace HaoZiTeam\AIPost\Service\Features;

defined('ABSPATH') || exit;

use HaoZiTeam\ChatGPT\V2;
use HaoZiTeam\AIPost\Service\Features\WenXinClient;
use HaoZiTeam\AIPost\Service\Features\SecureSettings;
use Exception;

class ApiClientService
{
    /**
     * 根据设置创建并返回一个 API 客户端实例 (V2)。
     *
     * @param array $settings 插件的全局设置。
     * @param string $task_key 当前任务的键名。
     * @param array $task_config 当前任务的特定配置。
     * @return V2|null V2 客户端实例，如果创建失败则返回 null。
     */
    /**
     * 根据设置创建并返回一个 API 客户端实例。
     *
     * @param array $settings 插件的全局设置。
     * @param string $task_key 当前任务的键名。
     * @param array $task_config 当前任务的特定配置。
     * @return V2|WenXinClient|null 客户端实例，如果创建失败则返回 null。
     */
    public static function create_api_client(array $settings, string $task_key, array $task_config)
    {
        try {
            // 客户端初始化即检查一次字体目录与默认字体
            try { self::ensure_default_font_present(); } catch (\Throwable $e) { /* silent */ }
            $apiServerType = $settings['api-server-type'] ?? 'custom';

            $chat_gpt = null;

            // 优先使用插件自带 CA 证书，强制传给 Guzzle 的 verify 选项
            // 路径：wp-content/plugins/ai-post/resources/cacert.pem
            $pluginRoot = \dirname(__DIR__, 2); // 从 Service/Features 回到插件根目录
            $forcedCABundle = $pluginRoot . '/resources/cacert.pem';
            $verifyOption = @file_exists($forcedCABundle) ? $forcedCABundle : true; // 找不到则回退系统默认

            if ($apiServerType === 'deepseek') {
                $accounts = $settings['deepseek-accounts'] ?? [];
                $apiServer = 'https://api.deepseek.com/'; // Default DeepSeek API server
                // Ensure server URL ends with a slash
                if (substr($apiServer, -1) !== '/') {
                    $apiServer .= '/';
                }

                if (empty($accounts)) {
                    return null;
                }

                $index = rand(1, count($accounts));
                $account = $accounts[$index - 1];

                $model_selection = $account['model-selection'] ?? 'deepseek-chat';
                $custom_model_name = $account['custom-model-name'] ?? '';

                if ($model_selection === 'custom') {
                    $selectedModel = !empty($custom_model_name) ? $custom_model_name : 'deepseek-chat';
                } else {
                    $selectedModel = $model_selection;
                }
                
                $apiKey = $account['account-secret-key'] ?? '';
                // 安全存储回退：deepseek 仅回退 deepseek_key
                if (empty($apiKey)) {
                    $secKey = SecureSettings::get('deepseek_key');
                    if (is_string($secKey) && $secKey !== '') { $apiKey = trim($secKey); }
                }

                // 安全存储回退：openai/custom 回退 openai_key / custom_key
                if (empty($apiKey)) {
                    $secKey = SecureSettings::get('openai_key');
                    if (!$secKey && ($apiServerType === 'custom' || $apiServerType === '')) {
                        $secKey = SecureSettings::get('custom_key');
                    }
                    if (is_string($secKey) && $secKey !== '') { $apiKey = trim($secKey); }
                }
                if (empty($apiKey)) {
                    return null;
                }

                $chat_gpt = new V2(
                    $apiKey,
                    $apiServer,
                    $selectedModel,
                    null, // proxy
                    null, // proxy_auth
                    360,  // timeout
                    [
                        'is_deepseek' => true,
                        'headers' => [
                            'Authorization' => 'Bearer ' . $apiKey,
                            'Content-Type' => 'application/json'
                        ],
                        'verify' => $verifyOption
                    ]
                );

            } elseif ($apiServerType === 'doubao') {
                $accounts = $settings['doubao-accounts'] ?? [];
                $apiServer = 'https://ark.cn-beijing.volces.com/api/v3/'; // Default Doubao API server
                // Ensure server URL ends with a slash and remove chat/completions if present
                if (substr($apiServer, -1) !== '/') {
                    $apiServer .= '/';
                }
                $apiServer = rtrim($apiServer, 'chat/completions/'); // Remove if it's part of the base URL input
                 if (substr($apiServer, -1) !== '/') { // Ensure it ends with a slash after potential rtrim
                    $apiServer .= '/';
                }

                if (empty($accounts)) {
                    return null;
                }

                $index = rand(1, count($accounts));
                $account = $accounts[$index - 1];

                $model_selection = $account['model-selection'] ?? 'doubao-1.5-pro-32k-250115'; // Default model
                $custom_model_name = $account['custom-model-name'] ?? '';

                if ($model_selection === 'custom') {
                    $selectedModel = !empty($custom_model_name) ? $custom_model_name : 'doubao-1.5-pro-32k-250115';
                } else {
                    $selectedModel = $model_selection;
                }
                
                $apiKey = $account['account-secret-key'] ?? '';
                // 安全存储回退：doubao 回退 doubao_key
                if (empty($apiKey)) {
                    $secKey = SecureSettings::get('doubao_key');
                    if (is_string($secKey) && $secKey !== '') { $apiKey = trim($secKey); }
                }
                if (empty($apiKey)) {
                    return null;
                }

                $chat_gpt = new V2(
                    $apiKey,
                    $apiServer,
                    $selectedModel,
                    null, // proxy
                    null, // proxy_auth
                    360,  // timeout
                    [
                        'is_doubao' => true,
                        'temperature' => $account['temperature'] ?? 0.7,
                        'headers' => [
                            'Authorization' => 'Bearer ' . $apiKey,
                            'Content-Type' => 'application/json'
                        ],
                        'verify' => $verifyOption
                    ]
                );

            } elseif ($apiServerType === 'bai-lian') {
                $accounts = $settings['bai-lian-accounts'] ?? [];
                $apiServer = 'https://dashscope.aliyuncs.com/compatible-mode/v1/'; // 阿里百炼兼容模式API服务器
                // 确保服务器URL以斜杠结尾
                if (substr($apiServer, -1) !== '/') {
                    $apiServer .= '/';
                }

                if (empty($accounts)) {
                    return null;
                }

                $index = rand(1, count($accounts));
                $account = $accounts[$index - 1];

                $model_selection = $account['model-selection'] ?? 'qwen-plus'; // 默认模型
                $custom_model_name = $account['custom-model-name'] ?? '';

                if ($model_selection === 'custom') {
                    $selectedModel = !empty($custom_model_name) ? $custom_model_name : 'qwen-plus';
                } else {
                    $selectedModel = $model_selection;
                }
                
                $apiKey = $account['account-secret-key'] ?? '';
                // 确保密钥没有多余空格
                $apiKey = trim($apiKey);
                if (empty($apiKey)) {
                    $secKey = SecureSettings::get('bailian_key');
                    if (is_string($secKey) && $secKey !== '') { $apiKey = trim($secKey); }
                }
                if (empty($apiKey)) {
                    return null;
                }

                // 获取温度设置
                $temperature = $account['temperature'] ?? 0.7;
                $temperature = (float)$temperature; // 确保类型正确

                $chat_gpt = new V2(
                    $apiKey,
                    $apiServer,
                    $selectedModel,
                    $temperature, // 传递温度参数
                    null, // topP
                    360,  // timeout
                    [
                        'is_bai_lian' => true,
                        'headers' => [
                            'Authorization' => 'Bearer ' . $apiKey,
                            'Content-Type' => 'application/json'
                        ],
                        'verify' => $verifyOption
                    ]
                );

            } elseif ($apiServerType === 'openai' || $apiServerType === 'custom' || empty($apiServerType)) { // OpenAI兼容或默认分支
                $apiServer = $settings['openai-api-server'] ?? 'https://sk.slapi.cn/';
                $apiKey = '';
                $selectedModel = 'gpt-3.5-turbo'; // Default model

                // Prioritize task-specific account configuration if available
                if (isset($task_config['account']) && !empty($task_config['account']['account-secret-key'])) {
                    $apiKey = $task_config['account']['account-secret-key'];
                    $selectedModel = $task_config['account']['model-selection'] ?? $selectedModel;
                    // $apiServer might also be overridden by task-specific settings if desired in the future
                }
                // Fallback to global openai-accounts array
                elseif (isset($settings['openai-accounts']) && !empty($settings['openai-accounts'])) {
                    $accounts = $settings['openai-accounts'];
                    $index = rand(1, count($accounts));
                    $account = $accounts[$index - 1];
                    $apiKey = $account['account-secret-key'] ?? '';
                    $selectedModel = $account['model-selection'] ?? $selectedModel;
                     // $apiServer might also be overridden by specific account in global array if desired
                }
                // Fallback to legacy cardPwd / cardNum
                elseif (!empty($settings['cardPwd'])) {
                    $apiKey = $settings['cardPwd'];
                    // Try to use task-configured model if available, otherwise default
                    $selectedModel = $task_config['model-selection'] ?? $selectedModel; 
                }
                elseif (!empty($settings['cardNum'])) {
                    $apiKey = $settings['cardNum'];
                    $selectedModel = $task_config['model-selection'] ?? $selectedModel;
                }

                if (empty($apiKey)) {
                    return null;
                }
                
                // 规范化 OpenAI 兼容服务器地址：确保以单一 /v1/ 结尾，避免缺失或重复 /v1
                $apiServer = trim($apiServer);
                // 去除尾部多余斜杠，之后统一追加
                $apiServer = rtrim($apiServer, "/\t\n\r ");
                // 如果末尾未包含 /v1 或 /v1/，则补上 /v1
                if (!preg_match('#/v1/?$#', $apiServer)) {
                    $apiServer = rtrim($apiServer, '/') . '/v1';
                }
                // 统一保证以斜杠结尾
                if (substr($apiServer, -1) !== '/') {
                    $apiServer .= '/';
                }

                $chat_gpt = new V2(
                    $apiKey,
                    $apiServer,
                    $selectedModel,
                    null, // proxy
                    null, // proxy_auth
                    360,  // timeout (秒)
                    [
                        'headers' => [
                            'Authorization' => 'Bearer ' . $apiKey,
                            'Content-Type' => 'application/json'
                        ],
                        'verify' => $verifyOption
                    ]
                );
            } elseif ($apiServerType === 'wenxin') {
                $accounts = $settings['wenxin-accounts'] ?? [];
                
                if (empty($accounts)) {
                    // 安全存储回退（无账号项时尝试）：仅当 secure 中存在键值时使用
                    $apiKey = SecureSettings::get('wenxin_key');
                    if (is_string($apiKey) && $apiKey !== '') {
                        // 若仅提供了 apiKey 而无 secret 无法调用，仍返回 null
                    }
                    return null;
                }

                $index = rand(1, count($accounts));
                $account = $accounts[$index - 1];

                $model_selection = $account['model-selection'] ?? 'ernie-4.0-8k';
                $apiKey = $account['api-key'] ?? '';
                $secretKey = $account['secret-key'] ?? '';
                if (empty($apiKey) || empty($secretKey)) {
                    $sec = SecureSettings::get('wenxin_key');
                    // 仅当安全存储内能解析出 apiKey:secretKey 形式时才使用
                    if (is_string($sec) && strpos($sec, ':') !== false) {
                        list($ak, $sk) = explode(':', $sec, 2);
                        $ak = trim((string)$ak); $sk = trim((string)$sk);
                        if ($ak !== '' && $sk !== '') { $apiKey = $ak; $secretKey = $sk; }
                    }
                }

                if (empty($apiKey) || empty($secretKey)) {
                    return null;
                }

                // 仅允许温度透传，其余参数在客户端内固定为合理默认
                $defaultOptions = [];
                if (isset($account['temperature']) && $account['temperature'] !== '') {
                    $defaultOptions['temperature'] = (float)$account['temperature'];
                }

                $chat_gpt = new WenXinClient(
                    $apiKey,
                    $secretKey,
                    $model_selection,
                    $defaultOptions
                );
            }
        } catch (Exception $e) {
            return null;
        }

        return $chat_gpt;
    }

} 