<?php

namespace XZD\AI\V5\Tools;

class AutomationManager
{
    /** 创建写文章计划 */
    public static function createWritePlan(array $params, int $userId): ToolResult
    {
        global $wpdb;
        $table = $wpdb->prefix . 'xzd_ai_write_plans';
        $wpdb->insert($table, [
            'name'        => $params['name'] ?? '',
            'keywords'    => $params['keywords'] ?? '',
            'category_id' => (int) ($params['category_id'] ?? 0),
            'schedule'    => $params['schedule'] ?? 'daily',
            'post_count'  => (int) ($params['post_count'] ?? 1),
            'enabled'     => ($params['enabled'] ?? true) ? 1 : 0,
            'next_run'    => current_time('mysql'),
            'created_at'  => current_time('mysql'),
            'updated_at'  => current_time('mysql'),
        ]);
        return ToolResult::success(['plan_id' => $wpdb->insert_id], '写文章计划已创建');
    }

    /** 立即写文章 */
    public static function triggerWriteNow(array $params, int $userId): ToolResult
    {
        $planId = (int) ($params['plan_id'] ?? 0);
        if ($planId) {
            global $wpdb;
            $plan = $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM {$wpdb->prefix}xzd_ai_write_plans WHERE id = %d", $planId
            ), ARRAY_A);
            if ($plan) {
                return ContentManager::writeArticle([
                    'topic'       => $plan['name'],
                    'keywords'    => $plan['keywords'],
                    'category_id' => $plan['category_id'],
                    'post_status' => $params['post_status'] ?? 'draft',
                ], $userId);
            }
            return ToolResult::error('计划不存在');
        }
        return ContentManager::writeArticle($params, $userId);
    }

    /** 查看队列 */
    public static function viewQueue(array $params, int $userId): ToolResult
    {
        global $wpdb;
        $table = $wpdb->prefix . 'xzd_ai_queue';
        $rows = $wpdb->get_results(
            "SELECT * FROM {$table} ORDER BY priority DESC, created_at ASC LIMIT 50",
            ARRAY_A
        );
        return ToolResult::success(['queue' => $rows ?: [], 'total' => count($rows ?: [])]);
    }

    // ═══ 自动化规则管理工具（9个） ═══

    /** 获取可用触发事件 */
    public static function getAvailableEvents(array $params, int $userId): ToolResult
    {
        $events = RuleEngine::instance()->getAvailableEvents();
        return ToolResult::success(['events' => $events], '可用触发事件');
    }

    /** 获取可用动作 */
    public static function getAvailableActions(array $params, int $userId): ToolResult
    {
        $actions = RuleEngine::instance()->getAvailableActions();
        return ToolResult::success(['actions' => $actions], '可用动作列表');
    }

    /** 创建自动化规则 */
    public static function createRule(array $params, int $userId): ToolResult
    {
        $name = $params['name'] ?? '';
        if (empty($name)) {
            return ToolResult::error('规则名称不能为空');
        }

        $event = $params['event'] ?? '';
        if (empty($event)) {
            return ToolResult::error('触发事件不能为空');
        }

        // 验证所有 tool_id 存在于 ToolRegistry
        $actions = $params['actions'] ?? [];
        if (is_string($actions)) {
            $actions = json_decode($actions, true);
        }
        if (is_array($actions)) {
            foreach ($actions as $action) {
                $toolId = $action['tool_id'] ?? '';
                if (!empty($toolId) && !ToolRegistry::instance()->has($toolId)) {
                    return ToolResult::error("工具不存在: {$toolId}");
                }
            }
        }

        $id = RuleEngine::instance()->createRule([
            'name'           => $name,
            'description'    => $params['description'] ?? '',
            'event'          => $event,
            'conditions'     => $params['conditions'] ?? null,
            'actions'        => $actions,
            'enabled'        => $params['enabled'] ?? 0,
            'created_by'     => 'ai',
            'operator_id'    => $userId,
            'rule_type'      => $params['rule_type'] ?? 'permanent',
            'expires_at'     => $params['expires_at'] ?? null,
            'max_executions' => (int)($params['max_executions'] ?? 0),
        ]);

        return ToolResult::success(['rule_id' => $id], "自动化规则「{$name}」已创建");
    }

    /** 列出所有规则 */
    public static function listRules(array $params, int $userId): ToolResult
    {
        $rules = RuleEngine::instance()->getAllRules();
        return ToolResult::success(['rules' => $rules, 'total' => count($rules)]);
    }

    /** 查看单条规则 */
    public static function getRule(array $params, int $userId): ToolResult
    {
        $ruleId = (int)($params['rule_id'] ?? 0);
        if (!$ruleId) {
            return ToolResult::error('请提供 rule_id');
        }

        $rule = RuleEngine::instance()->getRule($ruleId);
        if (!$rule) {
            return ToolResult::error('规则不存在');
        }

        return ToolResult::success(['rule' => $rule]);
    }

    /** 更新规则 */
    public static function updateRule(array $params, int $userId): ToolResult
    {
        $ruleId = (int)($params['rule_id'] ?? 0);
        if (!$ruleId) {
            return ToolResult::error('请提供 rule_id');
        }

        $data = [];
        foreach (['name', 'description', 'event', 'conditions', 'actions', 'enabled'] as $f) {
            if (isset($params[$f])) {
                $data[$f] = $params[$f];
            }
        }

        RuleEngine::instance()->updateRule($ruleId, $data);
        return ToolResult::success(['rule_id' => $ruleId], '规则已更新');
    }

    /** 删除规则 */
    public static function deleteRule(array $params, int $userId): ToolResult
    {
        $ruleId = (int)($params['rule_id'] ?? 0);
        if (!$ruleId) {
            return ToolResult::error('请提供 rule_id');
        }

        RuleEngine::instance()->deleteRule($ruleId);
        return ToolResult::success(['rule_id' => $ruleId], '规则已删除');
    }

    /** 启用/禁用规则 */
    public static function toggleRule(array $params, int $userId): ToolResult
    {
        $ruleId = (int)($params['rule_id'] ?? 0);
        if (!$ruleId) {
            return ToolResult::error('请提供 rule_id');
        }

        $newState = RuleEngine::instance()->toggleRule($ruleId);
        if ($newState === null) {
            return ToolResult::error('规则不存在');
        }

        $msg = $newState ? '规则已启用' : '规则已禁用';
        return ToolResult::success(['rule_id' => $ruleId, 'enabled' => $newState], $msg);
    }

    /** 手动执行规则 */
    public static function runRule(array $params, int $userId): ToolResult
    {
        $ruleId = (int)($params['rule_id'] ?? 0);
        if (!$ruleId) {
            return ToolResult::error('请提供 rule_id');
        }

        $rule = RuleEngine::instance()->getRule($ruleId);
        if (!$rule) {
            return ToolResult::error('规则不存在');
        }

        // 构建上下文
        $context = $params['context'] ?? [];
        if (empty($context)) {
            $context = ['triggered_by' => 'manual', 'user_id' => $userId];
        }

        $results = RuleEngine::instance()->evaluate($rule->event, $context);

        return ToolResult::success([
            'rule_id' => $ruleId,
            'rule_name' => $rule->name,
            'results' => $results,
        ], "规则「{$rule->name}」已手动执行");
    }

    // ═══ V7 阶段D：对话工具增强 ═══

    /** 批量处理：按范围筛选文章并创建批量流水线任务 */
    public static function batchProcess(array $params, int $userId): ToolResult
    {
        $range = $params['range'] ?? 'recent';
        $maxPosts = min((int)($params['max_posts'] ?? 50), 200);
        $stages = $params['stages'] ?? [];

        // 解析文章列表
        $postIds = self::resolvePostIds($params, $range, $maxPosts);

        if (empty($postIds)) {
            return ToolResult::success(['batch_id' => null, 'total' => 0, 'message' => '没有找到符合条件的文章']);
        }

        // 验证阶段
        if (empty($stages)) {
            $stages = ['generate_tags', 'generate_seo', 'generate_summary'];
        }
        $bp = new BatchPipeline();
        $availableStages = array_keys($bp->getAvailableStages());
        foreach ($stages as $i => $s) {
            if (!in_array($s, $availableStages)) {
                unset($stages[$i]);
            }
        }
        $stages = array_values($stages);
        if (empty($stages)) {
            return ToolResult::error('没有有效的流水线阶段');
        }

        $batchId = $bp->createBatch($postIds, $stages, [
            'batch_size' => min((int)($params['batch_size'] ?? 0), 25) ?: null,
        ]);
        $progress = $bp->getProgress($batchId);

        return ToolResult::success([
            'batch_id' => $batchId,
            'total'    => count($postIds),
            'stages'   => $stages,
            'progress' => $progress,
        ], "批量任务已创建，共 " . count($postIds) . " 篇文章");
    }

    /** 根据参数解析文章ID列表 */
    private static function resolvePostIds(array $params, string $range, int $maxPosts): array
    {
        $postStatus = $params['post_status'] ?? 'publish';

        // 直接指定ID
        if ($range === 'ids' && !empty($params['post_ids'])) {
            $ids = is_array($params['post_ids']) ? $params['post_ids'] : array_map('trim', explode(',', $params['post_ids']));
            return array_slice(array_map('intval', $ids), 0, $maxPosts);
        }

        // 日期范围
        if ($range === 'date_range') {
            return self::queryPostsByDate(
                $params['date_from'] ?? date('Y-m-d', strtotime('-30 days')),
                $params['date_to'] ?? date('Y-m-d'),
                $params['category_id'] ?? 0,
                $postStatus,
                $maxPosts
            );
        }

        // 分类筛选
        if ($range === 'category' && !empty($params['category_id'])) {
            return self::queryPostsByCategory((int)$params['category_id'], $postStatus, $maxPosts);
        }

        // 全部
        if ($range === 'all') {
            return self::queryPostsAll($postStatus, $maxPosts);
        }

        // 默认：recent — 最近30天
        return self::queryPostsByDate(
            date('Y-m-d', strtotime('-30 days')),
            date('Y-m-d'),
            $params['category_id'] ?? 0,
            $postStatus,
            $maxPosts
        );
    }

    private static function queryPostsByDate(string $dateFrom, string $dateTo, int $categoryId, string $postStatus, int $limit): array
    {
        global $wpdb;
        $sql = $wpdb->prepare(
            "SELECT p.ID FROM {$wpdb->posts} p
             LEFT JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
             WHERE p.post_type = %s AND p.post_status = %s
             AND p.post_date >= %s AND p.post_date <= %s",
            'post', $postStatus, $dateFrom . ' 00:00:00', $dateTo . ' 23:59:59'
        );
        if ($categoryId > 0) {
            $sql .= $wpdb->prepare(" AND tr.term_taxonomy_id = %d", $categoryId);
        }
        $sql .= $wpdb->prepare(" GROUP BY p.ID ORDER BY p.post_date DESC LIMIT %d", $limit);
        return array_map('intval', $wpdb->get_col($sql));
    }

    private static function queryPostsByCategory(int $categoryId, string $postStatus, int $limit): array
    {
        global $wpdb;
        $sql = $wpdb->prepare(
            "SELECT p.ID FROM {$wpdb->posts} p
             INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
             WHERE p.post_type = %s AND p.post_status = %s AND tr.term_taxonomy_id = %d
             GROUP BY p.ID ORDER BY p.post_date DESC LIMIT %d",
            'post', $postStatus, $categoryId, $limit
        );
        return array_map('intval', $wpdb->get_col($sql));
    }

    private static function queryPostsAll(string $postStatus, int $limit): array
    {
        global $wpdb;
        $sql = $wpdb->prepare(
            "SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND post_status = %s ORDER BY post_date DESC LIMIT %d",
            'post', $postStatus, $limit
        );
        return array_map('intval', $wpdb->get_col($sql));
    }

    /** 创建定时写文章规则 */
    public static function scheduleWrite(array $params, int $userId): ToolResult
    {
        $topic = $params['topic'] ?? '';
        if (empty($topic)) {
            return ToolResult::error('写作主题(topic)不能为空');
        }

        $scheduleHours = $params['schedule_hours'] ?? [8];
        if (is_string($scheduleHours)) {
            $scheduleHours = array_map('intval', explode(',', $scheduleHours));
        }
        $scheduleHours = array_map('intval', (array)$scheduleHours);

        // 构建 write_article 动作参数
        $actionParams = [
            'topic'              => $topic,
            'keywords'           => $params['keywords'] ?? '',
            'category_id'        => (int)($params['category_id'] ?? 0),
            'post_status'        => $params['post_status'] ?? 'draft',
            'tags'               => $params['tags'] ?? '',
            'illustration_count' => (int)($params['illustration_count'] ?? 2),
            'image_source'       => $params['image_source'] ?? 'stock',
            'generate_cover'     => $params['generate_cover'] ?? true,
            'generate_seo'       => $params['generate_seo'] ?? true,
            'daily_max'          => (int)($params['daily_max'] ?? 3),
        ];

        $ruleName = $params['name'] ?? "定时写文章: {$topic}";
        $scheduleHours = array_unique(array_map(fn($h) => max(0, min(23, (int)$h)), $scheduleHours));
        sort($scheduleHours);

        // 一条规则，多个触发时段（current_hour 匹配 cron 传递的整数小时）
        $id = RuleEngine::instance()->createRule([
            'name'        => $ruleName,
            'description' => "每天 " . implode('、', array_map(fn($h) => "{$h}:00", $scheduleHours)) . " 自动写一篇关于「{$topic}」的文章",
            'event'       => 'xzd_ai_schedule_write',
            'conditions'  => json_encode(['current_hour' => ['in' => $scheduleHours]], JSON_UNESCAPED_UNICODE),
            'actions'     => json_encode([['tool_id' => 'write_article', 'params' => $actionParams]], JSON_UNESCAPED_UNICODE),
            'enabled'     => $params['enabled'] ?? 1,
            'created_by'  => 'ai',
            'operator_id' => $userId,
            'rule_type'   => 'permanent',
        ]);
        $ids = [$id];

        $timeDesc = implode('、', array_map(fn($h) => "{$h}:00", $scheduleHours));
        return ToolResult::success([
            'rule_ids'       => $ids,
            'schedule_hours' => $scheduleHours,
            'topic'          => $topic,
        ], "定时写文章规则已创建，每天 {$timeDesc} 自动写一篇关于「{$topic}」的文章");
    }

    /** 列出定时写文章规则 */
    public static function listScheduledWrites(array $params, int $userId): ToolResult
    {
        $rules = RuleEngine::instance()->getAllRules();
        $scheduled = array_filter($rules, fn($r) => ($r->event ?? '') === 'xzd_ai_schedule_write');

        $result = [];
        foreach ($scheduled as $rule) {
            $actions = is_string($rule->actions) ? json_decode($rule->actions, true) : (array)($rule->actions ?? []);
            $conditions = is_string($rule->conditions) ? json_decode($rule->conditions, true) : (array)($rule->conditions ?? []);
            $firstAction = !empty($actions) ? $actions[0] : null;
            $hours = $conditions['current_hour']['in'] ?? ($conditions['current_hour'] ? [$conditions['current_hour']] : []);
            $result[] = [
                'rule_id'       => $rule->id,
                'name'          => $rule->name,
                'enabled'       => (bool)($rule->enabled ?? false),
                'schedule_hours'=> $hours,
                'topic'         => $firstAction['params']['topic'] ?? '',
                'post_status'   => $firstAction['params']['post_status'] ?? 'draft',
                'illustrations' => $firstAction['params']['illustration_count'] ?? 2,
                'created_at'    => $rule->created_at ?? '',
            ];
        }

        return ToolResult::success([
            'scheduled_writes' => $result,
            'total'            => count($result),
        ]);
    }

    /** 删除定时写文章规则 */
    public static function deleteScheduledWrite(array $params, int $userId): ToolResult
    {
        $ruleId = (int)($params['rule_id'] ?? 0);
        if (!$ruleId) {
            return ToolResult::error('请提供 rule_id');
        }

        $rule = RuleEngine::instance()->getRule($ruleId);
        if (!$rule) {
            return ToolResult::error('规则不存在');
        }

        if (($rule->event ?? '') !== 'xzd_ai_schedule_write') {
            return ToolResult::error('该规则不是定时写文章规则');
        }

        RuleEngine::instance()->deleteRule($ruleId);
        return ToolResult::success(['rule_id' => $ruleId], '定时写文章规则已删除');
    }

    /** 查看处理队列状态 */
    public static function checkQueue(array $params, int $userId): ToolResult
    {
        $status = QueueManager::getQueueStatus();

        // 补充 Action Scheduler 中的活跃Worker数
        $activeWorkers = 0;
        if (function_exists('as_get_scheduled_actions')) {
            $activeWorkers = count(as_get_scheduled_actions([
                'hook'     => 'xzd_worker_process',
                'status'   => \ActionScheduler_Store::STATUS_RUNNING,
                'group'    => 'xzd_worker',
                'per_page' => -1,
            ]));
        }

        return ToolResult::success([
            'queue'          => $status,
            'active_workers' => $activeWorkers,
            'healthy'        => ($status['queue_pending'] ?? 0) < 100,
        ]);
    }

    /** 查看Worker运行状态 */
    public static function workerStatus(array $params, int $userId): ToolResult
    {
        if (!class_exists(\XZD\AI\V5\Analytics\WorkerMonitor::class)) {
            return ToolResult::error('Worker监控模块未加载');
        }

        $status = \XZD\AI\V5\Analytics\WorkerMonitor::getStatus();
        $heartbeat = \XZD\AI\V5\Analytics\WorkerMonitor::getHeartbeat();

        return ToolResult::success([
            'status'    => $status,
            'heartbeat' => $heartbeat,
        ]);
    }
}
