<?php

namespace XZD\AI\V5\REST\Controllers;

use XZD\AI\V5\REST\BaseController;
use XZD\AI\V5\AI\Client;
use XZD\AI\V5\AI\ProviderFactory;
use WP_REST_Request;

/**
 * AI 连接管理 REST 端点
 *
 * POST /ai/test-connection  — 测试单个连接
 * POST /ai/test-all          — 测试所有连接
 * GET  /ai/models            — 获取模型列表
 */
class AIConnectionController extends BaseController
{
    public function registerRoutes(): void
    {
        $this->registerPost('/ai/test-connection', [$this, 'testConnection'], 'manage_options');
        $this->registerPost('/ai/test-all', [$this, 'testAll'], 'manage_options');
        $this->registerGet('/ai/models', [$this, 'getModels'], 'manage_options');
    }

    /**
     * 测试单个连接
     *
     * 支持两种模式:
     *   1. 传完整连接数据 — 用于测试新建/编辑中的连接（api_key 为明文）
     *   2. 传 pool + index — 用于测试已保存的连接（后端从数据库取真实密钥）
     */
    public function testConnection(WP_REST_Request $request): \WP_REST_Response
    {
        if ($err = $this->guardLicense('free')) return $err;
        $connection = $this->getBodyParams($request);

        // ★ 模式2: 按索引从数据库取真实密钥
        if (!empty($connection['_by_index'])) {
            $pool  = $connection['_pool'] ?? 'text';
            $index = (int) ($connection['_index'] ?? 0);
            $config = \XZD\AI\V5\Core\Config::instance();
            $saved  = $config->get("connections.{$pool}", []);
            if (!isset($saved[$index])) {
                return $this->error('连接不存在', 'connection_not_found');
            }
            $connection = $saved[$index];
            // ★ 解密已保存的密钥
            if (!empty($connection['api_key'])) {
                $connection['api_key'] = $config->decrypt($connection['api_key']);
            }
        }

        if (empty($connection) || empty($connection['api_key'] ?? '')) {
            return $this->error('请提供完整的连接配置', 'invalid_connection');
        }

        $client = Client::instance();
        $result = $client->testConnection($connection);

        if ($result['success']) {
            return $this->success($result);
        }
        return $this->error($result['message'] ?? '连接失败', 'connection_failed', 400, $result);
    }

    /**
     * 测试所有已配置的连接
     */
    public function testAll(WP_REST_Request $request): \WP_REST_Response
    {
        if ($err = $this->guardLicense('free')) return $err;
        $client = Client::instance();
        $results = $client->testAllConnections();

        return $this->success([
            'results' => $results,
            'total'   => count($results),
            'healthy' => count(array_filter($results, fn($r) => $r['success'] ?? false)),
        ]);
    }

    /**
     * 获取厂商模型列表
     */
    public function getModels(WP_REST_Request $request): \WP_REST_Response
    {
        if ($err = $this->guardLicense('free')) return $err;
        $connection = [
            'provider' => $request->get_param('provider'),
            'api_key'  => $request->get_param('api_key'),
            'base_url' => $request->get_param('base_url'),
            'model'    => $request->get_param('model'),
        ];

        if (empty($connection['api_key'])) {
            return $this->error('请提供 API Key', 'missing_api_key');
        }

        $client = Client::instance();
        $result = $client->getModels($connection);

        if ($result['success']) {
            return $this->success($result);
        }
        return $this->error($result['error'] ?? '获取模型失败', 'models_failed', 400, $result);
    }
}
