<?php

namespace XZD\AI\V5\Tools;

use XZD\AI\V5\Core\Config;

/**
 * 配置管理工具 — 将后台所有开关暴露为 AI 可调用的工具
 *
 * 所有方法返回 ToolResult，由 ToolRegistry 统一调度执行。
 * 权限: 全部要求 min_role='admin'，在 ToolRegistrar 注册层控制。
 */
class ConfigManager
{
    // ═══════════════════════════════════════════
    // 流水线管理 (4)
    // ═══════════════════════════════════════════

    /**
     * 查看流水线配置
     */
    public static function getPipelineConfig(array $params, int $userId): ToolResult
    {
        $config = Config::instance();
        $pipeline = $config->get('pipeline', []);

        $stages = $pipeline['stages'] ?? [];
        $asyncStages = $pipeline['async_stages'] ?? [];
        $triggers = $pipeline['triggers'] ?? [];
        $exclude = $pipeline['exclude'] ?? [];
        $event = $pipeline['event'] ?? 'publish';

        // 格式化输出
        $syncList = array_map(fn($s) => [
            'id'      => $s['id'] ?? '',
            'enabled' => $s['enabled'] ?? false,
        ], $stages);

        $asyncList = array_map(fn($s) => [
            'id'      => $s['id'] ?? '',
            'enabled' => $s['enabled'] ?? false,
        ], $asyncStages);

        return ToolResult::success([
            'event'        => $event,
            'sync_stages'  => $syncList,
            'async_stages' => $asyncList,
            'triggers'     => $triggers,
            'exclude'      => $exclude,
        ], '流水线配置');
    }

    /**
     * 启用/禁用流水线阶段
     *
     * @param array $params ['stage_id' => 'generate_tags', 'enabled' => true/false]
     */
    public static function togglePipelineStage(array $params, int $userId): ToolResult
    {
        $stageId = $params['stage_id'] ?? '';
        $enabled = $params['enabled'] ?? null;

        if (empty($stageId)) {
            return ToolResult::error('请提供 stage_id（阶段ID）');
        }
        if ($enabled === null) {
            return ToolResult::error('请提供 enabled（true=启用, false=禁用）');
        }

        $config = Config::instance();
        $pipeline = $config->get('pipeline', []);

        // 查找同步阶段
        $found = false;
        $stages = $pipeline['stages'] ?? [];
        foreach ($stages as $i => $s) {
            if (($s['id'] ?? '') === $stageId) {
                $stages[$i]['enabled'] = (bool) $enabled;
                $found = true;
                break;
            }
        }

        // 查找异步阶段
        $asyncStages = $pipeline['async_stages'] ?? [];
        if (!$found) {
            foreach ($asyncStages as $i => $s) {
                if (($s['id'] ?? '') === $stageId) {
                    $asyncStages[$i]['enabled'] = (bool) $enabled;
                    $found = true;
                    break;
                }
            }
        }

        if (!$found) {
            // 列出可用阶段帮助AI纠正
            $allIds = array_merge(
                array_column($stages, 'id'),
                array_column($asyncStages, 'id')
            );
            return ToolResult::error("阶段不存在: {$stageId}。可用阶段: " . implode(', ', $allIds));
        }

        $pipeline['stages'] = $stages;
        $pipeline['async_stages'] = $asyncStages;
        $config->set('pipeline', $pipeline)->save();

        $action = $enabled ? '启用' : '禁用';
        return ToolResult::success(['stage_id' => $stageId, 'enabled' => (bool) $enabled], "流水线阶段「{$stageId}」已{$action}");
    }

    /**
     * 切换流水线触发条件
     */
    public static function togglePipelineTrigger(array $params, int $userId): ToolResult
    {
        $triggerKey = $params['trigger'] ?? '';
        $enabled = $params['enabled'] ?? null;

        $validTriggers = ['publish', 'update', 'schedule'];
        if (!in_array($triggerKey, $validTriggers, true)) {
            return ToolResult::error("无效触发条件: {$triggerKey}。可选: " . implode(', ', $validTriggers));
        }
        if ($enabled === null) {
            return ToolResult::error('请提供 enabled（true=启用, false=禁用）');
        }

        $config = Config::instance();
        $pipeline = $config->get('pipeline', []);
        $triggers = $pipeline['triggers'] ?? [];

        if ($enabled) {
            if (!in_array($triggerKey, $triggers, true)) {
                $triggers[] = $triggerKey;
            }
        } else {
            $triggers = array_values(array_diff($triggers, [$triggerKey]));
        }

        $pipeline['triggers'] = $triggers;
        $config->set('pipeline', $pipeline)->save();

        $action = $enabled ? '启用' : '禁用';
        return ToolResult::success(['trigger' => $triggerKey, 'enabled' => (bool) $enabled, 'triggers' => $triggers], "触发条件「{$triggerKey}」已{$action}");
    }

    /**
     * 设置流水线排除规则
     */
    public static function setPipelineExclude(array $params, int $userId): ToolResult
    {
        $config = Config::instance();
        $pipeline = $config->get('pipeline', []);
        $exclude = $pipeline['exclude'] ?? [];

        if (isset($params['categories'])) {
            $cats = is_array($params['categories']) ? $params['categories'] : explode(',', (string) $params['categories']);
            $exclude['categories'] = array_map('trim', $cats);
        }
        if (isset($params['post_ids'])) {
            $ids = is_array($params['post_ids']) ? $params['post_ids'] : array_map('intval', explode(',', (string) $params['post_ids']));
            $exclude['post_ids'] = $ids;
        }
        if (isset($params['min_words'])) {
            $exclude['min_words'] = (int) $params['min_words'];
        }

        $pipeline['exclude'] = $exclude;
        $config->set('pipeline', $pipeline)->save();

        return ToolResult::success(['exclude' => $exclude], '流水线排除规则已更新');
    }

    // ═══════════════════════════════════════════
    // 工具注册表管理 — 分角色三级控制 (6)
    // ═══════════════════════════════════════════

    /**
     * 查看所有工具及分角色启用/禁用状态
     */
    public static function listToolsStatus(array $params, int $userId): ToolResult
    {
        $registry = ToolRegistry::instance();
        $allTools = $registry->getAll();
        $blockedByRole = Config::instance()->get('tools.blocked_tools_by_role', []);
        $roles = ['guest', 'user', 'vip', 'admin'];

        $list = [];
        foreach ($allTools as $tool) {
            $perRole = [];
            foreach ($roles as $role) {
                $roleBlocked = $blockedByRole[$role] ?? [];
                $perRole[$role] = !in_array($tool->id, $roleBlocked, true);
            }
            $list[] = [
                'id'          => $tool->id,
                'name'        => $tool->name,
                'category'    => $tool->category,
                'min_role'    => $tool->minRole,
                'enabled_by_role' => $perRole,
                'description' => $tool->description,
            ];
        }

        // 按分类 + 角色统计
        $summary = [];
        foreach ($roles as $role) {
            $enabled = count(array_filter($list, fn($t) => $t['enabled_by_role'][$role] ?? false));
            $summary[$role] = ['total' => count($list), 'enabled' => $enabled];
        }

        return ToolResult::success([
            'tools'   => $list,
            'total'   => count($list),
            'summary' => $summary,
            'roles'   => $roles,
        ], '工具分角色状态');
    }

    /**
     * 对指定角色开关单个工具
     */
    public static function toggleToolForRole(array $params, int $userId): ToolResult
    {
        $toolId = $params['tool_id'] ?? '';
        $role   = $params['role'] ?? 'user';
        $enabled = $params['enabled'] ?? null;

        if (empty($toolId)) return ToolResult::error('请提供 tool_id');
        if (!in_array($role, ['guest', 'user', 'vip', 'admin'], true)) return ToolResult::error("无效角色: {$role}");
        if ($enabled === null) return ToolResult::error('请提供 enabled（true=启用, false=禁用）');

        $registry = ToolRegistry::instance();
        if (!$registry->has($toolId)) return ToolResult::error("工具不存在: {$toolId}");

        $config = Config::instance();
        $blockedByRole = $config->get('tools.blocked_tools_by_role', []);
        $roleBlocked = $blockedByRole[$role] ?? [];

        if ($enabled) {
            $roleBlocked = array_values(array_diff($roleBlocked, [$toolId]));
        } else {
            if (!in_array($toolId, $roleBlocked, true)) $roleBlocked[] = $toolId;
        }

        $blockedByRole[$role] = $roleBlocked;
        $config->set('tools.blocked_tools_by_role', $blockedByRole)->save();

        $tool = $registry->get($toolId);
        $action = $enabled ? '启用' : '禁用';
        return ToolResult::success([
            'role' => $role, 'tool_id' => $toolId, 'tool_name' => $tool->name, 'enabled' => $enabled,
        ], "{$role}角色的「{$tool->name}」已{$action}");
    }

    /**
     * 对指定角色批量启用工具
     */
    public static function enableToolsForRole(array $params, int $userId): ToolResult
    {
        $toolIds = $params['tool_ids'] ?? [];
        $role = $params['role'] ?? 'user';

        if (is_string($toolIds)) $toolIds = array_map('trim', explode(',', $toolIds));
        if (empty($toolIds)) return ToolResult::error('请提供 tool_ids（工具ID数组或逗号分隔）');
        if (!in_array($role, ['guest', 'user', 'vip', 'admin'], true)) return ToolResult::error("无效角色: {$role}");

        $config = Config::instance();
        $blockedByRole = $config->get('tools.blocked_tools_by_role', []);
        $roleBlocked = $blockedByRole[$role] ?? [];
        $roleBlocked = array_values(array_diff($roleBlocked, $toolIds));
        $blockedByRole[$role] = $roleBlocked;
        $config->set('tools.blocked_tools_by_role', $blockedByRole)->save();

        return ToolResult::success(['role' => $role, 'enabled' => $toolIds, 'count' => count($toolIds)], "已为{$role}角色启用 " . count($toolIds) . " 个工具");
    }

    /**
     * 对指定角色批量禁用工具
     */
    public static function disableToolsForRole(array $params, int $userId): ToolResult
    {
        $toolIds = $params['tool_ids'] ?? [];
        $role = $params['role'] ?? 'user';

        if (is_string($toolIds)) $toolIds = array_map('trim', explode(',', $toolIds));
        if (empty($toolIds)) return ToolResult::error('请提供 tool_ids');
        if (!in_array($role, ['guest', 'user', 'vip', 'admin'], true)) return ToolResult::error("无效角色: {$role}");

        $config = Config::instance();
        $blockedByRole = $config->get('tools.blocked_tools_by_role', []);
        $roleBlocked = $blockedByRole[$role] ?? [];
        foreach ($toolIds as $tid) {
            if (!in_array($tid, $roleBlocked, true)) $roleBlocked[] = $tid;
        }
        $blockedByRole[$role] = $roleBlocked;
        $config->set('tools.blocked_tools_by_role', $blockedByRole)->save();

        return ToolResult::success(['role' => $role, 'disabled' => $toolIds, 'count' => count($toolIds)], "已为{$role}角色禁用 " . count($toolIds) . " 个工具");
    }

    /**
     * 对指定角色一键全开/全关全部工具
     */
    public static function setAllToolsForRole(array $params, int $userId): ToolResult
    {
        $role = $params['role'] ?? 'user';
        $enabled = $params['enabled'] ?? null;

        if (!in_array($role, ['guest', 'user', 'vip', 'admin'], true)) return ToolResult::error("无效角色: {$role}");
        if ($enabled === null) return ToolResult::error('请提供 enabled（true=全开, false=全关）');

        $registry = ToolRegistry::instance();
        $allIds = array_map(fn($t) => $t->id, array_values($registry->getAll()));

        $config = Config::instance();
        $blockedByRole = $config->get('tools.blocked_tools_by_role', []);

        if ($enabled) {
            $blockedByRole[$role] = [];
        } else {
            $blockedByRole[$role] = $allIds;
        }

        $config->set('tools.blocked_tools_by_role', $blockedByRole)->save();

        $action = $enabled ? '全部启用' : '全部禁用';
        return ToolResult::success(['role' => $role, 'enabled' => $enabled, 'total' => count($allIds)], "{$role}角色已{$action} " . count($allIds) . " 个工具");
    }

    /**
     * 启用/禁用指定工具（旧版兼容，全局开关）
     * @deprecated 使用 toggleToolForRole 代替
     */
    public static function toggleTool(array $params, int $userId): ToolResult
    {
        // 转调到分角色版本，默认操作 user 角色
        $params['role'] = $params['role'] ?? 'user';
        return self::toggleToolForRole($params, $userId);
    }

    // ═══════════════════════════════════════════
    // AI 连接池管理 (3)
    // ═══════════════════════════════════════════

    /**
     * 查看所有 AI 连接及状态
     */
    public static function listAiConnections(array $params, int $userId): ToolResult
    {
        $config = Config::instance();
        $textConns = $config->get('connections.text', []);
        $imageConns = $config->get('connections.image', []);

        $format = function (array $conns, string $type) {
            return array_map(fn($c, $i) => [
                'index'      => $i,
                'type'       => $type,
                'name'       => $c['name'] ?? '未命名',
                'provider'   => $c['provider'] ?? '',
                'model'      => $c['model'] ?? '',
                'is_primary' => (bool) ($c['is_primary'] ?? false),
                'is_enabled' => (bool) ($c['is_enabled'] ?? true),
            ], $conns, array_keys($conns));
        };

        return ToolResult::success([
            'text_connections'  => $format($textConns, 'text'),
            'image_connections' => $format($imageConns, 'image'),
            'total'             => count($textConns) + count($imageConns),
        ], 'AI 连接列表');
    }

    /**
     * 启用/禁用指定 AI 连接
     */
    public static function toggleAiConnection(array $params, int $userId): ToolResult
    {
        $type = $params['type'] ?? 'text'; // text 或 image
        $index = (int) ($params['index'] ?? 0);
        $enabled = $params['enabled'] ?? null;

        if (!in_array($type, ['text', 'image'], true)) {
            return ToolResult::error('type 必须为 text 或 image');
        }
        if ($enabled === null) {
            return ToolResult::error('请提供 enabled（true=启用, false=禁用）');
        }

        $config = Config::instance();
        $conns = $config->get("connections.{$type}", []);

        if (!isset($conns[$index])) {
            return ToolResult::error("连接不存在: {$type}[{$index}]，共 " . count($conns) . " 个连接");
        }

        $conns[$index]['is_enabled'] = (bool) $enabled;
        $config->set("connections.{$type}", $conns)->save();

        $name = $conns[$index]['name'] ?? "{$type}[{$index}]";
        $action = $enabled ? '启用' : '禁用';
        return ToolResult::success(['type' => $type, 'index' => $index, 'enabled' => (bool) $enabled], "连接「{$name}」已{$action}");
    }

    /**
     * 设置主用 AI 连接
     */
    public static function setPrimaryConnection(array $params, int $userId): ToolResult
    {
        $type = $params['type'] ?? 'text';
        $index = (int) ($params['index'] ?? 0);

        if (!in_array($type, ['text', 'image'], true)) {
            return ToolResult::error('type 必须为 text 或 image');
        }

        $config = Config::instance();
        $conns = $config->get("connections.{$type}", []);

        if (!isset($conns[$index])) {
            return ToolResult::error("连接不存在: {$type}[{$index}]");
        }

        // 全部取消主用
        foreach ($conns as $i => &$c) {
            $c['is_primary'] = ($i === $index);
        }

        $config->set("connections.{$type}", $conns)->save();

        $name = $conns[$index]['name'] ?? "{$type}[{$index}]";
        return ToolResult::success(['type' => $type, 'index' => $index, 'name' => $name], "「{$name}」已设为主用连接");
    }

    // ═══════════════════════════════════════════
    // 速率与费用管理 (2)
    // ═══════════════════════════════════════════

    /**
     * 查看速率限制配置
     */
    public static function getRateConfig(array $params, int $userId): ToolResult
    {
        $config = Config::instance();
        $rateLimit = $config->get('rate_limit', []);
        $cost = $config->get('cost', []);

        return ToolResult::success([
            'rate_limit' => $rateLimit,
            'cost'       => [
                'monthly_budget'     => $cost['monthly_budget'] ?? 0,
                'over_budget_action' => $cost['over_budget_action'] ?? 'warn',
            ],
        ], '速率与费用配置');
    }

    /**
     * 设置速率限制
     *
     * @param array $params ['role' => 'guest', 'daily' => 20, 'per_minute' => 5, 'interval' => 3]
     */
    public static function setRateConfig(array $params, int $userId): ToolResult
    {
        $role = $params['role'] ?? '';
        $validRoles = ['guest', 'user', 'vip', 'admin'];

        if (!in_array($role, $validRoles, true)) {
            return ToolResult::error("无效角色: {$role}。可选: " . implode(', ', $validRoles));
        }

        $config = Config::instance();
        $rateLimit = $config->get('rate_limit', []);

        if (!isset($rateLimit[$role])) {
            $rateLimit[$role] = [];
        }

        if (isset($params['daily'])) {
            $rateLimit[$role]['daily'] = (int) $params['daily'];
        }
        if (isset($params['per_minute'])) {
            $rateLimit[$role]['per_minute'] = (int) $params['per_minute'];
        }
        if (isset($params['interval'])) {
            $rateLimit[$role]['interval'] = (int) $params['interval'];
        }
        if (isset($params['unlimited']) && $role === 'admin') {
            $rateLimit[$role]['unlimited'] = (bool) $params['unlimited'];
        }

        $config->set('rate_limit', $rateLimit);

        // 费用设置
        if (isset($params['monthly_budget'])) {
            $config->set('cost.monthly_budget', (float) $params['monthly_budget']);
        }
        if (isset($params['over_budget_action'])) {
            $config->set('cost.over_budget_action', $params['over_budget_action']);
        }

        $config->save();

        return ToolResult::success([
            'role'      => $role,
            'rate_limit' => $rateLimit[$role],
        ], "{$role} 角色速率限制已更新");
    }

    // ═══════════════════════════════════════════
    // AI 身份与摘要显示 (3)
    // ═══════════════════════════════════════════

    /**
     * 设置 AI 身份
     */
    public static function setAiIdentity(array $params, int $userId): ToolResult
    {
        $config = Config::instance();

        if (isset($params['user_id'])) {
            $config->set('ai_identity.user_id', (int) $params['user_id']);
        }
        if (isset($params['name'])) {
            $config->set('ai_identity.name', $params['name']);
        }
        if (isset($params['avatar'])) {
            $config->set('ai_identity.avatar', $params['avatar']);
        }

        $config->save();

        $identity = $config->resolveAIIdentity();
        return ToolResult::success(['ai_identity' => $identity], 'AI 身份已更新');
    }

    /**
     * 查看摘要显示配置
     */
    public static function getSummaryConfig(array $params, int $userId): ToolResult
    {
        $config = Config::instance();

        return ToolResult::success([
            'enabled'   => $config->bool('summary.enabled', $config->bool('summary_enabled', true)),
            'animation' => $config->bool('summary.animation', $config->bool('summary_animation', false)),
            'title'     => $config->get('summary.title', $config->get('summary_title', 'AI智能摘要')),
            'badge'     => $config->get('summary.badge', $config->get('summary_badge', 'AI')),
            'style'     => $config->get('summary.style', $config->get('summary_style', '')),
        ], '摘要显示配置');
    }

    /**
     * 设置摘要显示
     */
    public static function setSummaryConfig(array $params, int $userId): ToolResult
    {
        $config = Config::instance();

        $validStyles = ['', 'glass', 'neon', 'minimal', 'terminal', 'warm', 'neumorph', 'editorial', 'chat', 'pixel', 'sticky', 'aurora', 'menghuan', 'simple', 'floating'];

        if (isset($params['enabled'])) {
            $config->set('summary.enabled', (bool) $params['enabled']);
        }
        if (isset($params['animation'])) {
            $config->set('summary.animation', (bool) $params['animation']);
        }
        if (isset($params['title'])) {
            $config->set('summary.title', $params['title']);
        }
        if (isset($params['badge'])) {
            $config->set('summary.badge', $params['badge']);
        }
        if (isset($params['style'])) {
            if (!in_array($params['style'], $validStyles, true)) {
                return ToolResult::error("无效风格: {$params['style']}。可选: " . implode(', ', $validStyles));
            }
            $config->set('summary.style', $params['style']);
        }

        $config->save();

        return ToolResult::success([
            'enabled'   => $config->bool('summary.enabled', true),
            'animation' => $config->bool('summary.animation', false),
            'title'     => $config->get('summary.title', 'AI智能摘要'),
            'badge'     => $config->get('summary.badge', 'AI'),
            'style'     => $config->get('summary.style', ''),
        ], '摘要显示配置已更新');
    }

    // ═══════════════════════════════════════════
    // V3.1.5 友链配置管理
    // ═══════════════════════════════════════════

    public static function getFriendLinkConfig(array $params, int $userId): ToolResult
    {
        $config = Config::instance();
        return ToolResult::success([
            'monitor_enabled'      => $config->bool('friend_link.monitor_enabled', false),
            'monitor_hour'         => $config->int('friend_link.monitor_hour', 2),
            'lost_alert_threshold' => $config->int('friend_link.lost_alert_threshold', 3),
        ], '友链配置');
    }

    public static function setFriendLinkConfig(array $params, int $userId): ToolResult
    {
        $config = Config::instance();

        if (isset($params['monitor_enabled'])) {
            $config->set('friend_link.monitor_enabled', (bool)$params['monitor_enabled']);
        }
        if (isset($params['monitor_hour'])) {
            $hour = max(0, min(23, (int)$params['monitor_hour']));
            $config->set('friend_link.monitor_hour', $hour);
        }
        if (isset($params['lost_alert_threshold'])) {
            $threshold = max(1, min(10, (int)$params['lost_alert_threshold']));
            $config->set('friend_link.lost_alert_threshold', $threshold);
        }

        $config->save();

        return ToolResult::success([
            'monitor_enabled'      => $config->bool('friend_link.monitor_enabled', false),
            'monitor_hour'         => $config->int('friend_link.monitor_hour', 2),
            'lost_alert_threshold' => $config->int('friend_link.lost_alert_threshold', 3),
        ], '友链配置已更新');
    }
}
