<?php

namespace XZD\AI\V5\REST\Controllers;

use XZD\AI\V5\REST\BaseController;
use XZD\AI\V5\Core\LicenseService;
use WP_REST_Request;

/**
 * 授权管理 REST 端点
 *
 * GET    /license/status      — 查询授权状态
 * POST   /license/activate    — 激活授权
 * POST   /license/deactivate  — 撤销授权
 * GET    /license/notice      — 获取公告/更新日志
 * POST   /license/check-update — 检查更新
 * POST   /license/do-update   — 执行在线更新
 */
class LicenseController extends BaseController
{
    private LicenseService $svc;

    public function __construct()
    {
        $this->svc = LicenseService::instance();
    }

    public function registerRoutes(): void
    {
        $this->registerGet('/license/status', [$this, 'status'], 'manage_options');
        $this->registerPost('/license/activate', [$this, 'activate'], 'manage_options');
        $this->registerPost('/license/deactivate', [$this, 'deactivate'], 'manage_options');
        $this->registerGet('/license/notice', [$this, 'notice'], 'manage_options');
        $this->registerPost('/license/check-update', [$this, 'checkUpdate'], 'manage_options');
        $this->registerPost('/license/do-update', [$this, 'doUpdate'], 'manage_options');
    }

    /**
     * 查询授权状态（含三级等级信息）
     */
    public function status(WP_REST_Request $request): \WP_REST_Response
    {
        $data = $this->svc->getLicenseData();
        $level = $data['level'] ?? 'free';

        return $this->success(array_merge($data, [
            'features'   => $this->getFeatureList($level),
            'level_info' => \XZD\AI\V5\Core\ToolPermissions::getLevelInfo($level),
            'is_local'   => $data['is_local'] ?? false,
            'sysinfo'    => $this->getSystemInfo(),
        ]));
    }

    /**
     * 系统环境信息
     */
    private function getSystemInfo(): array
    {
        return [
            'os'     => PHP_OS,
            'server' => $_SERVER['SERVER_SOFTWARE'] ?? '—',
            'php'    => PHP_VERSION,
            'upload' => ini_get('upload_max_filesize'),
            'wp'     => get_bloginfo('version'),
            'time'   => current_time('mysql'),
        ];
    }

    /**
     * 激活授权（含三级等级判断 + 旗舰版自动启动知识库学习）
     */
    public function activate(WP_REST_Request $request): \WP_REST_Response
    {
        try {
            $code = $this->getParam($request, 'code', '');

            $result = $this->svc->activate($code);

            if (!$result['success']) {
                return $this->error($result['message'], 'activate_failed');
            }

            $licenseData = $this->svc->getLicenseData();
            $level = $licenseData['level'] ?? 'pro';
            $postActions = [];

            // ★ 旗舰版激活后自动启动知识库学习
            if ($level === 'ultimate') {
                if (class_exists(\XZD\AI\V5\Tools\LearningEngine::class)
                    && function_exists('as_schedule_single_action')) {
                    as_schedule_single_action(
                        time() + 30,
                        'xzd_ai_learning_run',
                        ['mode' => 'incremental'],
                        'xzd_learning'
                    );
                    $postActions[] = 'knowledge_learning_scheduled';
                }
            }

            if ($level !== 'free') {
                $postActions[] = 'pro_features_unlocked';
            }

            $reminder = match ($level) {
                'ultimate' => '旗舰版已激活，知识库学习将在30秒后自动启动。其他高级功能已全部解锁。',
                'pro'      => '专业版已激活，自动化和媒体处理功能已解锁。建议前往设置页面配置流水线和自动化规则。',
                default    => null,
            };

            return $this->success([
                'status'       => $licenseData['status'],
                'level'        => $level,
                'level_info'   => \XZD\AI\V5\Core\ToolPermissions::getLevelInfo($level),
                'expire_at'    => $licenseData['expire_at'] ?? null,
                'features'     => $this->getFeatureList($level),
                'post_actions' => $postActions,
                'reminder'     => $reminder,
            ], $result['message']);
        } catch (\Throwable $e) {
            return $this->error('服务器内部错误: ' . $e->getMessage(), 'internal_error', 500);
        }
    }

    /**
     * 撤销授权
     */
    public function deactivate(WP_REST_Request $request): \WP_REST_Response
    {
        $result = $this->svc->deactivate();

        if (!$result['success']) {
            return $this->error($result['message'], 'deactivate_failed');
        }

        return $this->success([
            'status'     => 'inactive',
            'level'      => 'free',
            'level_info' => \XZD\AI\V5\Core\ToolPermissions::getLevelInfo('free'),
            'expire_at'  => null,
            'features'   => $this->getFeatureList('free'),
        ], $result['message']);
    }

    /**
     * 获取公告/更新日志
     *
     * Query: ?refresh=1 强制刷新缓存
     */
    public function notice(WP_REST_Request $request): \WP_REST_Response
    {
        $force = $this->getBoolParam($request, 'refresh', false);

        if ($force) {
            $data = $this->svc->refreshNoticeAndSync();
        } else {
            $data = $this->svc->getNotice(false);
            $data['history'] = $this->svc->getNoticeHistory();
        }

        return $this->success($data);
    }

    /**
     * 检查更新
     */
    public function checkUpdate(WP_REST_Request $request): \WP_REST_Response
    {
        $result = $this->svc->checkUpdate();

        if (!$result['success']) {
            return $this->error($result['message'], 'check_update_failed');
        }

        return $this->success($result);
    }

    /**
     * 执行在线更新
     */
    public function doUpdate(WP_REST_Request $request): \WP_REST_Response
    {
        $downloadUrl = $this->getParam($request, 'download_url', '');

        if (empty($downloadUrl)) {
            return $this->error('缺少下载地址', 'missing_url');
        }

        $result = $this->svc->doUpdate($downloadUrl);

        if (!$result['success']) {
            return $this->error($result['message'], 'update_failed');
        }

        return $this->success(null, $result['message']);
    }

    /**
     * 三级功能清单 — 每项标记最低需要等级和当前是否锁定
     */
    private function getFeatureList(string $level): array
    {
        $levelOrder = ['free' => 0, 'pro' => 1, 'ultimate' => 2];
        $currentOrder = $levelOrder[$level] ?? 0;

        $all = [
            ['name' => 'AI对话',        'desc' => '不限模型不限次数',      'icon' => 'chat',       'min_level' => 'free'],
            ['name' => '内容引擎',        'desc' => '12款内容创作工具',       'icon' => 'content',    'min_level' => 'free'],
            ['name' => 'SEO工具集',       'desc' => '5款搜索引擎优化工具',    'icon' => 'seo',        'min_level' => 'free'],
            ['name' => '只读查询',        'desc' => '网站数据查询工具',       'icon' => 'query',      'min_level' => 'free'],
            ['name' => '在线更新与公告',   'desc' => '自动更新与版本公告',     'icon' => 'update',     'min_level' => 'free'],
            ['name' => '流水线编排',      'desc' => '自动化内容处理流程',     'icon' => 'pipeline',   'min_level' => 'pro'],
            ['name' => '自动化规则引擎',   'desc' => '智能触发与定时任务',     'icon' => 'automation', 'min_level' => 'pro'],
            ['name' => '媒体工具',        'desc' => 'WebP转换/水印处理',     'icon' => 'media',      'min_level' => 'pro'],
            ['name' => 'AI写文章',       'desc' => 'AI自动写作+配图',      'icon' => 'write',      'min_level' => 'pro'],
            ['name' => 'WP站点管理',      'desc' => '文章/评论/分类管理',     'icon' => 'users',      'min_level' => 'pro'],
            ['name' => '多Agent协作',     'desc' => '分布式智能体系统',       'icon' => 'agent',      'min_level' => 'pro'],
            ['name' => '主动介入AI',      'desc' => 'Proactive智能建议',    'icon' => 'proactive',  'min_level' => 'pro'],
            ['name' => '知识库管理',       'desc' => 'AI智能学习与检索',      'icon' => 'knowledge',  'min_level' => 'ultimate'],
            ['name' => '用户管理(高级)',   'desc' => '用户/角色/权限管理',     'icon' => 'users',      'min_level' => 'ultimate'],
            ['name' => '主题适配',        'desc' => 'Zibll主题深度集成',     'icon' => 'theme',      'min_level' => 'ultimate'],
        ];

        return array_map(function ($item) use ($currentOrder, $levelOrder) {
            $minOrder = $levelOrder[$item['min_level']] ?? 0;
            return [
                'name'      => $item['name'],
                'desc'      => $item['desc'],
                'icon'      => $item['icon'],
                'min_level' => $item['min_level'],
                'locked'    => $currentOrder < $minOrder,
            ];
        }, $all);
    }
}
