<?php

namespace XZD\AI\V5\Tools;

use XZD\AI\V5\AI\Client;
use XZD\AI\V5\AI\Types;
use XZD\AI\V5\Core\Config;
use XZD\AI\V5\Core\PreserveDates;

/**
 * WordPress 管理工具 — 20个 CRUD/站点管理工具
 */
class WPManager
{
    // ===== 文章 CRUD =====

    public static function createPost(array $params, int $userId): ToolResult
    {
        $id = wp_insert_post([
            'post_title'   => $params['title'] ?? '',
            'post_content' => $params['content'] ?? '',
            'post_status'  => $params['status'] ?? 'draft',
            'post_type'    => $params['post_type'] ?? 'post',
            'post_author'  => $userId,
            'post_category' => isset($params['category_id']) ? [(int) $params['category_id']] : [],
        ], true);

        if (is_wp_error($id)) return ToolResult::error($id->get_error_message());
        return ToolResult::success(['post_id' => $id, 'url' => get_permalink($id)], '文章已创建', ['undo_data' => ['post_id' => $id]]);
    }

    public static function updatePost(array $params, int $userId): ToolResult
    {
        $id = (int) ($params['post_id'] ?? 0);
        $data = [];
        foreach (['title' => 'post_title', 'content' => 'post_content', 'status' => 'post_status'] as $k => $col) {
            if (isset($params[$k])) $data[$col] = $params[$k];
        }
        $data['ID'] = $id;
        $result = PreserveDates::updatePost($data, true); // true=用户手动操作，正常更新日期
        if (is_wp_error($result)) return ToolResult::error($result->get_error_message());
        return ToolResult::success(['post_id' => $id], '文章已更新', ['undo_data' => ['post_id' => $id, 'previous' => get_post($id)->to_array()]]);
    }

    public static function deletePost(array $params, int $userId): ToolResult
    {
        $id = (int) ($params['post_id'] ?? 0);
        $force = (bool) ($params['force'] ?? false);
        $post = get_post($id);
        if (!$post) return ToolResult::error('文章不存在');
        $result = wp_delete_post($id, $force);
        if (!$result) return ToolResult::error('删除失败');
        return ToolResult::success(null, '文章已' . ($force ? '永久删除' : '移入回收站'));
    }

    public static function publishPost(array $params, int $userId): ToolResult
    {
        $id = (int) ($params['post_id'] ?? 0);
        $result = PreserveDates::updatePost(['ID' => $id, 'post_status' => 'publish'], true);
        if (is_wp_error($result)) return ToolResult::error($result->get_error_message());
        return ToolResult::success(['post_id' => $id, 'url' => get_permalink($id)], '文章已发布');
    }

    public static function getPost(array $params, int $userId): ToolResult
    {
        $id = (int) ($params['post_id'] ?? 0);
        $post = get_post($id);
        if (!$post) return ToolResult::error('文章不存在');

        $data = [
            'id' => $post->ID, 'title' => $post->post_title,
            'status' => $post->post_status, 'author' => get_the_author_meta('display_name', $post->post_author),
            'date' => $post->post_date, 'modified' => $post->post_modified,
            'url' => get_permalink($post), 'comment_count' => $post->comment_count,
        ];

        // ★ 管理员可见：完整 AI 处理数据
        if (current_user_can('manage_options')) {
            $data['ai_data'] = self::collectAIData($id);
        }

        return ToolResult::success($data);
    }

    /**
     * 收集文章所有 AI 处理数据（管理员可见）
     */
    private static function collectAIData(int $postId): array
    {
        $ai = [];

        // 现有标签
        $tags = wp_get_post_tags($postId, ['fields' => 'names']);
        $ai['现有标签'] = is_array($tags) ? $tags : [];
        $ai['标签数量'] = count($ai['现有标签']);

        // AI 处理标记（哪些工具处理过、何时处理）
        $markers = [];
        $trackedTools = [
            'generate_tags' => 'AI标签', 'generate_seo' => 'SEO优化', 'generate_summary' => 'AI摘要',
            'polish_content' => '内容润色', 'translate_content' => '内容翻译', 'rewrite_content' => '内容改写',
            'expand_content' => '内容扩展', 'generate_cover' => '封面图', 'generate_alt' => 'ALT文字',
            'build_autolink' => '内链构建', 'score_quality' => '质量评分',
        ];
        foreach ($trackedTools as $toolId => $toolLabel) {
            $marker = get_post_meta($postId, '_xzd_ai_processed_' . $toolId, true);
            if (!empty($marker) && ($marker['status'] ?? '') === 'completed') {
                $markers[$toolLabel] = [
                    '处理时间' => $marker['timestamp'] ?? '',
                    '处理模式' => $marker['mode'] ?? '',
                    '结果摘要' => $marker['summary'] ?? '',
                ];
            }
        }
        $ai['处理历史'] = $markers;

        // SEO 数据
        $seoTitle = get_post_meta($postId, '_xzd_ai_seo_title', true);
        $seoKeys = get_post_meta($postId, '_xzd_ai_seo_keywords', true);
        $seoDesc = get_post_meta($postId, '_xzd_ai_seo_description', true);
        if ($seoTitle || $seoKeys || $seoDesc) {
            $ai['SEO数据'] = ['标题' => $seoTitle ?: '', '关键词' => $seoKeys ?: '', '描述' => $seoDesc ?: ''];
        }

        // 摘要
        $summary = get_post_meta($postId, '_xzd_ai_summary', true);
        if ($summary) $ai['AI摘要'] = $summary;

        // 润色版本
        $polished = get_post_meta($postId, '_xzd_ai_polished', true);
        $polishedList = get_post_meta($postId, '_xzd_ai_polished_list', true);
        if ($polished && !$polishedList) $ai['润色版本'] = ['当前版本数' => 1];
        if ($polishedList) $ai['润色版本'] = ['历史版本数' => count($polishedList)];

        // 翻译
        $translatedLangs = [];
        foreach (['en' => '英文', 'ja' => '日文', 'ko' => '韩文', 'zh' => '中文'] as $lc => $ln) {
            if (get_post_meta($postId, '_xzd_ai_translated_' . $lc, true)) $translatedLangs[] = $ln;
        }
        if ($translatedLangs) $ai['已翻译语言'] = $translatedLangs;

        // 改写风格
        $rewrittenStyles = [];
        foreach (['professional' => '专业化', 'casual' => '通俗化', 'creative' => '创意化'] as $sk => $sv) {
            if (get_post_meta($postId, '_xzd_ai_rewritten_' . $sk, true)) $rewrittenStyles[] = $sv;
        }
        if ($rewrittenStyles) $ai['已改写风格'] = $rewrittenStyles;

        // 扩展
        if (get_post_meta($postId, '_xzd_ai_expanded', true)) $ai['已扩展'] = true;

        // 封面图
        $coverPrompt = get_post_meta($postId, '_xzd_ai_cover_prompt', true);
        if ($coverPrompt) $ai['封面描述词'] = $coverPrompt;

        // 内链
        $autolinks = get_post_meta($postId, '_xzd_ai_autolinks', true);
        if ($autolinks) $ai['内链'] = ['数量' => count($autolinks), '链接' => $autolinks];

        // 质量评分
        $qualityScore = get_post_meta($postId, '_xzd_ai_quality_score', true);
        if ($qualityScore) $ai['质量评分'] = $qualityScore;

        // ALT 文字
        $altTexts = get_post_meta($postId, '_xzd_ai_alt_texts', true);
        if ($altTexts) $ai['ALT文字'] = ['图片数' => count($altTexts)];

        return $ai;
    }

    public static function searchPosts(array $params, int $userId): ToolResult
    {
        $query = new \WP_Query([
            's' => $params['keyword'] ?? '',
            'post_type' => $params['post_type'] ?? 'post',
            'post_status' => $params['post_status'] ?? 'publish',
            'posts_per_page' => min((int) ($params['per_page'] ?? 20), 100),
            'paged' => (int) ($params['page'] ?? 1),
            'cat' => $params['category_id'] ?? 0,
        ]);
        $posts = array_map(fn($p) => ['id' => $p->ID, 'title' => $p->post_title, 'status' => $p->post_status, 'date' => $p->post_date, 'url' => get_permalink($p->ID)], $query->posts);
        wp_reset_postdata();
        return ToolResult::success(['posts' => $posts, 'total' => $query->found_posts]);
    }

    // ===== 用户管理 =====

    public static function listUsers(array $params, int $userId): ToolResult
    {
        $users = get_users(['number' => min((int) ($params['per_page'] ?? 20), 100), 'paged' => (int) ($params['page'] ?? 1)]);
        $list = array_map(fn($u) => ['id' => $u->ID, 'name' => $u->display_name, 'email' => $u->user_email, 'role' => implode(',', $u->roles)], $users);
        return ToolResult::success(['users' => $list, 'total' => count_users()['total_users'] ?? 0]);
    }

    public static function getUser(array $params, int $userId): ToolResult
    {
        $id = (int) ($params['user_id'] ?? 0);
        $u = get_userdata($id);
        if (!$u) return ToolResult::error('用户不存在');
        return ToolResult::success(['id' => $u->ID, 'name' => $u->display_name, 'email' => $u->user_email, 'role' => implode(',', $u->roles), 'registered' => $u->user_registered]);
    }

    public static function createUser(array $params, int $userId): ToolResult
    {
        $login = $params['username'] ?? $params['name'] ?? '';
        $id = wp_insert_user(['user_login' => $login, 'user_pass' => $params['password'] ?? wp_generate_password(), 'user_email' => $params['email'] ?? '', 'display_name' => $params['display_name'] ?? $login, 'role' => $params['role'] ?? 'subscriber']);
        if (is_wp_error($id)) return ToolResult::error($id->get_error_message());
        return ToolResult::success(['user_id' => $id], '用户已创建', ['undo_data' => ['user_id' => $id]]);
    }

    public static function updateUser(array $params, int $userId): ToolResult
    {
        $data = ['ID' => (int) ($params['user_id'] ?? 0)];
        foreach (['display_name', 'user_email', 'role'] as $f) {
            if (isset($params[$f])) $data[$f] = $params[$f];
        }
        $result = wp_update_user($data);
        if (is_wp_error($result)) return ToolResult::error($result->get_error_message());
        return ToolResult::success(null, '用户已更新');
    }

    public static function deleteUser(array $params, int $userId): ToolResult
    {
        require_once ABSPATH . 'wp-admin/includes/user.php';
        $id = (int) ($params['user_id'] ?? 0);
        if ($id === $userId) return ToolResult::error('不能删除自己');
        if (!wp_delete_user($id)) return ToolResult::error('删除失败');
        return ToolResult::success(null, '用户已删除');
    }

    public static function changeRole(array $params, int $userId): ToolResult
    {
        $uid = (int) ($params['user_id'] ?? 0);
        $role = $params['role'] ?? '';
        $u = get_userdata($uid);
        if (!$u) return ToolResult::error('用户不存在');
        $u->set_role($role);
        return ToolResult::success(null, "角色已更改为 {$role}");
    }

    // ===== 站点管理 =====

    public static function siteStats(array $params, int $userId): ToolResult
    {
        return ToolResult::success([
            'posts'     => wp_count_posts()->publish ?? 0,
            'pages'     => wp_count_posts('page')->publish ?? 0,
            'comments'  => wp_count_comments()->approved ?? 0,
            'users'     => count_users()['total_users'] ?? 0,
            'categories' => wp_count_terms('category'),
            'tags'      => wp_count_terms('post_tag'),
        ]);
    }

    public static function manageComments(array $params, int $userId): ToolResult
    {
        $action = $params['action'] ?? 'list';
        return match ($action) {
            'approve' => (wp_set_comment_status((int) ($params['comment_id'] ?? 0), 'approve') ? ToolResult::success(null, '已批准') : ToolResult::error('操作失败')),
            'spam'    => (wp_spam_comment((int) ($params['comment_id'] ?? 0)) ? ToolResult::success(null, '已标记为垃圾评论') : ToolResult::error('操作失败')),
            'trash'   => (wp_trash_comment((int) ($params['comment_id'] ?? 0)) ? ToolResult::success(null, '已移至回收站') : ToolResult::error('操作失败')),
            default   => self::listComments($params),
        };
    }

    public static function manageCategories(array $params, int $userId): ToolResult
    {
        $action = $params['action'] ?? 'list';
        return match ($action) {
            'create' => self::createCategory($params),
            'delete' => (wp_delete_category((int) ($params['category_id'] ?? 0)) ? ToolResult::success(null, '已删除') : ToolResult::error('删除失败')),
            default  => ToolResult::success(['categories' => get_categories(['hide_empty' => false])]),
        };
    }

    public static function manageTags(array $params, int $userId): ToolResult
    {
        $action = $params['action'] ?? 'list';
        return match ($action) {
            'create' => self::createTag($params),
            'delete' => (wp_delete_term((int) ($params['tag_id'] ?? 0), 'post_tag') ? ToolResult::success(null, '已删除') : ToolResult::error('删除失败')),
            default  => ToolResult::success(['tags' => get_tags(['hide_empty' => false])]),
        };
    }

    public static function listPlugins(array $params, int $userId): ToolResult
    {
        if (!function_exists('get_plugins')) require_once ABSPATH . 'wp-admin/includes/plugin.php';
        $plugins = [];
        foreach (get_plugins() as $file => $data) {
            $plugins[] = ['file' => $file, 'name' => $data['Name'], 'version' => $data['Version'], 'active' => is_plugin_active($file)];
        }
        return ToolResult::success(['plugins' => $plugins]);
    }

    public static function getSettings(array $params, int $userId): ToolResult
    {
        return ToolResult::success([
            'site_title' => get_option('blogname'),
            'tagline' => get_option('blogdescription'),
            'admin_email' => get_option('admin_email'),
            'timezone' => get_option('timezone_string'),
            'permalink' => get_option('permalink_structure'),
            'date_format' => get_option('date_format'),
        ]);
    }

    public static function clearCache(array $params, int $userId): ToolResult
    {
        wp_cache_flush();
        if (function_exists('w3tc_flush_all')) w3tc_flush_all();
        if (function_exists('wpfc_clear_all_cache')) wpfc_clear_all_cache(true);
        $deep = !empty($params['deep']);
        if ($deep) {
            self::cleanupPluginData($params, $userId);
        }
        return ToolResult::success(null, $deep ? '缓存及插件数据已深度清理' : '缓存已清除');
    }

    /**
     * 清理插件所有累积数据 — 日志/聊天/流分块/队列/遗留表
     */
    public static function cleanupPluginData(array $params, int $userId): ToolResult
    {
        global $wpdb;
        $days = max(1, (int)($params['retention_days'] ?? 7));
        $cutoff = date('Y-m-d H:i:s', strtotime("-{$days} days"));
        $cleaned = [];

        // 操作日志
        $n = $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->prefix}xzd_ai_operation_log WHERE created_at < %s", $cutoff
        ));
        if ($n > 0) $cleaned[] = "操作日志 {$n} 条";

        // 费用日志
        $n = $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->prefix}xzd_ai_cost_log WHERE created_at < %s", $cutoff
        ));
        if ($n > 0) $cleaned[] = "费用日志 {$n} 条";

        // 自动化日志
        $n = $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->prefix}xzd_ai_automation_logs WHERE created_at < %s", $cutoff
        ));
        if ($n > 0) $cleaned[] = "自动化日志 {$n} 条";

        // 已删除会话及消息
        $oldSessions = $wpdb->get_col($wpdb->prepare(
            "SELECT session_key FROM {$wpdb->prefix}xzd_ai_chat_sessions WHERE status = 'deleted' AND updated_at < %s", $cutoff
        ));
        if (!empty($oldSessions)) {
            $placeholders = implode(',', array_fill(0, count($oldSessions), '%s'));
            $wpdb->query($wpdb->prepare(
                "DELETE FROM {$wpdb->prefix}xzd_ai_chat_messages WHERE session_key IN ($placeholders)", ...$oldSessions
            ));
            $wpdb->query($wpdb->prepare(
                "DELETE FROM {$wpdb->prefix}xzd_ai_chat_sessions WHERE session_key IN ($placeholders)", ...$oldSessions
            ));
            $cleaned[] = '已删除会话 ' . count($oldSessions) . ' 个';
        }

        // 过期流分块
        $n = $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->prefix}xzd_ai_chat_stream_chunks WHERE created_at < %s", $cutoff
        ));
        if ($n > 0) $cleaned[] = "流分块 {$n} 条";

        // 任务队列（已完成/失败）
        $n = $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->prefix}xzd_ai_queue WHERE status IN ('completed','failed') AND processed_at < %s", $cutoff
        ));
        if ($n > 0) $cleaned[] = "任务队列 {$n} 条";

        // V2 遗留日志
        $n = $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->prefix}xzd_ai_logs WHERE created_at < %s", $cutoff
        ));
        if ($n > 0) $cleaned[] = "遗留日志 {$n} 条";

        // 写文章追踪（已完成）
        $n = $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->prefix}xzd_ai_write_articles WHERE status = 'completed' AND created_at < %s", $cutoff
        ));
        if ($n > 0) $cleaned[] = "写文章追踪 {$n} 条";

        // 清空WP对象缓存
        wp_cache_flush();

        $msg = empty($cleaned) ? '无过期数据需要清理' : '已清理: ' . implode(' + ', $cleaned);
        return ToolResult::success(['retention_days' => $days, 'cleaned' => $cleaned], $msg);
    }

    public static function replyComment(array $params, int $userId): ToolResult
    {
        $commentId = (int) ($params['comment_id'] ?? 0);
        $replyContent = $params['content'] ?? '';
        $parent = get_comment($commentId);
        if (!$parent) return ToolResult::error('评论不存在');

        // 身份回退：AI绑定用户 → 文章作者 → admin
        if (!$userId) {
            $identity = Config::instance()->resolveAIIdentity();
            $userId = $identity['user_id'] ?: 0;
        }
        if (!$userId) {
            $post = get_post($parent->comment_post_ID);
            $userId = $post ? $post->post_author : 1;
        }

        // 无预设内容时，调用AI智能生成回复
        if (empty(trim($replyContent))) {
            $post = get_post($parent->comment_post_ID);
            if (!$post) return ToolResult::error('文章不存在');

            $postContent = mb_substr(wp_strip_all_tags(strip_shortcodes($post->post_content)), 0, 3000);
            $commentText = $parent->comment_content;

            $prompt = "你是「{$post->post_title}」的AI助手，用户评论了这篇文章。\n\n"
                . "【文章内容】\n{$postContent}\n\n"
                . "【用户评论】{$commentText}\n\n"
                . "判断评论类型并回复：\n"
                . "1. 关于文章内容的问题 → 基于文章详细解答\n"
                . "2. 赞美/感谢 → 友好回应并鼓励互动\n"
                . "3. 建议/批评 → 虚心接受并感谢\n"
                . "4. 垃圾评论 → 回复空字符串\n\n"
                . "用中文回复，50-300字，自然友好，不要以「回复：」开头。";

            try {
                $result = Client::instance()->chat(
                    [Types::user($prompt)],
                    ['max_tokens' => 500]
                );
                $replyContent = trim($result['content'] ?? '');
            } catch (\Throwable $e) {
                return ToolResult::error('AI生成回复失败: ' . $e->getMessage());
            }

            if (empty($replyContent)) {
                return ToolResult::success(['skipped' => true], '评论无需回复');
            }
        }

        // 自动过审：优先使用工具参数，其次全局配置，默认自动过审
        $autoApprove = $params['auto_approve'] ?? Config::instance()->get('comment.auto_approve_reply', true);

        // 获取AI身份用户信息以填充 comment_author/email
        $aiUser = get_userdata($userId);
        $authorName = $aiUser ? $aiUser->display_name : get_bloginfo('name') . 'AI助手';
        $authorEmail = $aiUser ? $aiUser->user_email : '';

        $id = wp_new_comment([
            'comment_post_ID'   => $parent->comment_post_ID,
            'comment_parent'    => $commentId,
            'comment_content'   => $replyContent,
            'comment_author'    => $authorName,
            'comment_author_email' => $authorEmail,
            'user_id'           => $userId,
            'comment_approved'  => $autoApprove ? 1 : 0,
        ]);
        if (!$id) return ToolResult::error('回复失败');
        return ToolResult::success(['comment_id' => $id, 'content' => $replyContent], '回复成功');
    }

    // ===== 内部方法 =====

    private static function createCategory(array $params): ToolResult
    {
        $name   = $params['name'] ?? '';
        $parent = (int)($params['parent'] ?? 0);
        if (empty($name)) return ToolResult::error('分类名称不能为空');
        
        $result = wp_insert_term($name, 'category', ['parent' => $parent]);
        if (is_wp_error($result)) {
            return ToolResult::error($result->get_error_message());
        }
        return ToolResult::success(['id' => $result['term_id'], 'name' => $name], '分类已创建');
    }

    private static function createTag(array $params): ToolResult
    {
        $name = $params['name'] ?? '';
        if (empty($name)) return ToolResult::error('标签名称不能为空');
        
        $result = wp_insert_term($name, 'post_tag');
        if (is_wp_error($result)) {
            return ToolResult::error($result->get_error_message());
        }
        return ToolResult::success(['id' => $result['term_id'], 'name' => $name], '标签已创建');
    }

    private static function listComments(array $params): ToolResult
    {
        $comments = get_comments(['number' => min((int) ($params['per_page'] ?? 20), 100), 'status' => $params['status'] ?? 'approve']);
        $list = array_map(fn($c) => ['id' => $c->comment_ID, 'author' => $c->comment_author, 'content' => mb_substr($c->comment_content, 0, 100), 'post_id' => $c->comment_post_ID, 'date' => $c->comment_date], $comments);
        return ToolResult::success(['comments' => $list]);
    }

    /** 只读列出分类/标签 */
    public static function listTerms(array $params, int $userId): ToolResult
    {
        $taxonomy = $params['taxonomy'] ?? 'category';
        if (!in_array($taxonomy, ['category', 'post_tag'], true)) {
            return ToolResult::error('不支持的分类法: ' . $taxonomy);
        }
        $perPage = min((int)($params['per_page'] ?? 50), 100);
        $terms = get_terms([
            'taxonomy'   => $taxonomy,
            'hide_empty' => (bool)($params['hide_empty'] ?? false),
            'number'     => $perPage,
        ]);
        if (is_wp_error($terms)) {
            return ToolResult::error($terms->get_error_message());
        }
        $list = array_map(fn($t) => [
            'id'          => $t->term_id,
            'name'        => $t->name,
            'slug'        => $t->slug,
            'description' => $t->description ?: '',
            'count'       => $t->count,
        ], $terms);
        return ToolResult::success(['terms' => $list, 'total' => count($list), 'taxonomy' => $taxonomy]);
    }
}
