<?php

namespace XHTheme\AIToolbox;

defined('ABSPATH') || exit;

final class XHComment extends XHTool
{

    private static $instance;

    private $maxComments = 100;

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
            self::$instance->init();
        }
        return self::$instance;
    }

    private function __construct() {}


    public function init()
    {
        add_filter('admin_comment_types_dropdown', array($this, 'add_comment_types_dropdown'));
        add_filter('manage_edit-comments_columns', array($this, 'add_comment_columns'));
        add_action('manage_comments_custom_column', array($this, 'manage_comment_columns'), 10, 2);
        add_filter('get_avatar_comment_types', array($this, 'add_avatar_comment_types'));
        add_filter('get_comment_type', array($this, 'filter_comment_type'), 10, 2);
        add_filter('pre_get_avatar_data', array($this, 'handleAvatar'), 99, 2);
        add_filter('get_avatar_data', array($this, 'filter_avatar_data'), 99, 2);
        add_filter('pre_get_avatar', array($this, 'pre_get_avatar'), 99, 2);
        add_filter('get_user_metadata', array($this, 'user_metadata_filter'), 10, 4);
        add_action('xhaitoolbox_minute_cron', array($this, 'process_comment_status'), 5);
        add_filter('xhaitoolbox_cronitem_comment', array($this, 'process_ai_comments'), 10, 1);
        add_action('xhtheme_ai_toolbox_avatarloacal_error', array($this, 'avatarloacal_error'), 10, 1);
        add_filter('wp_list_comments_args', array($this, 'add_comment_type'));
        add_filter('comment_class', array($this, 'add_comment_class'), 10, 5);
        add_action('init', array($this, 'add_aiuser_role'));

        /**
         * 屏蔽邮件通知
         */
        add_filter('comment_notification_recipients', array($this, 'comment_notification'), 10, 2);
        add_filter('comment_moderation_recipients', array($this, 'comment_notification'), 10, 2);
        // 过滤虚拟邮箱收件人
        add_filter('wp_mail', array($this, 'filter_xmail_recipients'));
        add_filter('pre_wp_mail', array($this, 'prevent_xmail_sending'), 10, 2);
        /**
         * 为评论绑定用户
         */
        add_action('wp_set_comment_status', array($this, 'bind_comment_user'), 10, 2);
    }

    function filter_comment_type($comment_type, $commentId)
    {
        if ($comment_type == 'ai_comment' && is_singular()) {
            return 'comment';
        }
        return $comment_type;
    }

    function user_metadata_filter($value, $object_id, $meta_key, $single)
    {
        if ($meta_key === 'zib_other_data') {
            $user = get_user_by('ID', $object_id);
            $is_ai_user = $user && (
                in_array('xhaiuser', (array) $user->roles) ||
                get_user_meta($object_id, '_xhai_role', true) === 'xhaiuser'
            );
            if ($is_ai_user) {
                $userAvatar = $this->get_avatar_by_user($object_id);
                if (!empty($userAvatar)) {
                    $valueArr = [
                        'custom_avatar' => esc_url($userAvatar)
                    ];
                    return [$valueArr];
                }
            }
        }
        return $value;
    }

    public function pre_get_avatar($avatar, $id_or_email)
    {
        if (is_null($avatar) || xh_themeName() !== 'Zibll') {
            return $avatar;
        }

        $reststart = false;
        if (is_numeric($id_or_email)) {
            if ($id_or_email > 0) {
                $user = get_user_by('ID', $id_or_email);
                $is_ai_user = $user && (
                    in_array('xhaiuser', (array) $user->roles) ||
                    get_user_meta($id_or_email, '_xhai_role', true) === 'xhaiuser'
                );
                if ($is_ai_user) {
                    $reststart = true;
                }
            }
        } elseif (is_object($id_or_email)) {
            if ($id_or_email instanceof \WP_Comment) {
                if ($id_or_email->comment_type == 'ai_comment') {
                    $reststart = true;
                } else {
                    // 检查 AI Interact 评论（评论官/智能回评/随手一评）
                    $interact_type = get_comment_meta($id_or_email->comment_ID, '_ai_interact_type', true);
                    if (in_array($interact_type, ['moderator', 'reply', 'autoreply', 'randcomment'], true)) {
                        $reststart = true;
                    }
                }
            } elseif ($id_or_email instanceof \WP_User) {
                $is_ai_user = in_array('xhaiuser', (array) $id_or_email->roles) || get_user_meta($id_or_email->ID, '_xhai_role', true) === 'xhaiuser';
                if ($is_ai_user) {
                    $id_or_email = $id_or_email->ID;
                    $reststart = true;
                }
            }
        } elseif (is_string($id_or_email) && is_email($id_or_email)) {
            $reststart = true;
        }

        if ($reststart) {
            $avatarArr = $this->handleAvatar([], $id_or_email);
            if ($avatarArr && isset($avatarArr['aiavatarurl'])) {
                $new_avatar_url = $avatarArr['aiavatarurl'];
                if (strpos($avatar, '-src=') !== false) {
                    $avatar = preg_replace(
                        '/-src=[\'"]([^\'"]*)[\'"]/',
                        '-src="' . $new_avatar_url . '"',
                        $avatar,
                        1
                    );
                } else {
                    $avatar = preg_replace(
                        '/src=[\'"]([^\'"]*)[\'"]/',
                        'src="' . $new_avatar_url . '"',
                        $avatar,
                        1
                    );
                }
            }
        }
        return $avatar;
    }

    public function add_aiuser_role()
    {
        if (!get_role('xhaiuser')) {
            add_role(
                'xhaiuser',
                __('AI User', 'xhtheme-ai-toolbox'),
                array(
                    'read' => true
                )
            );
        }
    }

    public function bind_comment_user($comment_id, $comment_status)
    {
        if ($comment_status == 'approve' || $comment_status == '1') {
            $comment = get_comment($comment_id);
            if ($comment->comment_type == 'ai_comment') {
                $this->update_comment_user($comment);
            }
        }
    }

    public function update_comment_user($comment)
    {
        $user_id = $comment->user_id;
        if ($user_id) {
            return;
        }

        $commentuser = xh_option('commentuser', 'guest');

        if ($commentuser == 'guest') {
            return;
        }

        // 检查 _ai_guest_lock 标记（insertComment 中混合模式已决定为游客）
        $commentId = $comment->comment_ID;
        if (get_comment_meta($commentId, '_ai_guest_lock', true)) {
            delete_comment_meta($commentId, '_ai_guest_lock');
            return;
        }

        // 混合模式概率计算（仅作用于历史遗留的未标记评论）
        if ($commentuser === 'mixed') {
            $commentMixedRatio = xh_option('commentMixedRatio', 20);
            $random = wp_rand(1, 100);
            if ($random < $commentMixedRatio) {
                return;
            }
        }
        $userName = $comment->comment_author;
        $userEmail = $comment->comment_author_email;

        if (empty($userName) || empty($userEmail)) {
            return;
        }

        if (!is_email($userEmail)) {
            return;
        }

        $existing_user = email_exists($userEmail);

        if ($existing_user) {
            wp_update_comment(array(
                'comment_ID' => $commentId,
                'user_id' => $existing_user
            ));
            delete_comment_meta($commentId, '_ai_avatar');
            wp_cache_delete($existing_user, 'user_avatar');
            return;
        }

        // 检查是否存在相同昵称
        global $wpdb;
        $email_like = '%' . $wpdb->esc_like('@xmail.com');
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-time query for unique nickname check
        $Nickname = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT ID,user_email FROM {$wpdb->users} 
                 WHERE user_nicename = %s 
                 AND user_email LIKE %s",
                $userName,
                $email_like
            )
        );
        if ($Nickname) {
            $userId = $Nickname->ID;
            wp_update_comment(array(
                'comment_ID' => $commentId,
                'user_id' => $userId,
                'comment_author_email' => $Nickname->user_email
            ));
            delete_comment_meta($commentId, '_ai_avatar');
            wp_cache_delete($userId, 'user_avatar');
            return;
        }

        // 检查 AI 用户生成上限
        $ai_user_limit = (int) xh_option('aiUserLimit', 200);
        if ($this->get_ai_user_count() >= $ai_user_limit) {
            // 达到上限，复用已有 AI 用户
            $random_user = $this->get_random_aiuser($comment->comment_post_ID);
            if ($random_user) {
                wp_update_comment([
                    'comment_ID' => $commentId,
                    'user_id'    => $random_user->ID,
                ]);
                delete_comment_meta($commentId, '_ai_avatar');
            }
            return;
        }

        // 根据邮箱前缀生成用户名
        $user_login = substr($userEmail, 0, strpos($userEmail, '@'));
        $userAvatar = $this->get_ai_avatar($commentId);
        if ($user_login) {
            $userdata = array(
                'user_login' => 'xhai_' . $user_login,
                'user_email' => $userEmail,
                'user_pass' => wp_generate_password(12, false),
                'display_name' => $userName,
                'nickname' => $userName,
                'role' => 'xhaiuser'
            );
            $user_id = wp_insert_user($userdata);

            if (!is_wp_error($user_id)) {
                if (!empty($userAvatar)) {
                    update_user_meta($user_id, '_ai_avatar', $userAvatar);
                }
                wp_update_comment(array(
                    'comment_ID' => $commentId,
                    'user_id' => $user_id
                ));

                delete_comment_meta($commentId, '_ai_avatar');
                wp_cache_delete($user_id, 'user_avatar');
            }
        }
    }

    public function add_avatar_comment_types($comment_types)
    {
        $comment_types[] = 'ai_comment';
        return $comment_types;
    }

    /**
     * 处理头像
     */
    public function handleAvatar($args, $id_or_email)
    {
        if (is_string($id_or_email) && is_email($id_or_email)) {
            $email = $id_or_email;
            $email_suffix = '@xmail.com';
            if (substr($email, -strlen($email_suffix)) !== $email_suffix) {
                return $args;
            }

            $comments = get_comments(array(
                'author_email' => $email,
                'number' => 1
            ));
            if (!empty($comments)) {
                $id_or_email = $comments[0];
            } else {
                $user = get_user_by('email', $email);
                if ($user) {
                    $id_or_email = $user->ID;
                }
            }
        }

        if (!is_object($id_or_email) || !isset($id_or_email->comment_ID)) {
            if ((is_numeric($id_or_email) && $id_or_email > 0) || !in_the_loop()) {
                $userAvatar = $this->get_avatar_by_user($id_or_email);
                if ($userAvatar) {
                    $args['url'] = esc_url($userAvatar);
                    $args['aiavatarurl'] = $args['url'];
                }
                return $args;
            }
            global $comment;
            $id_or_email = $comment;
        }

        if (!is_object($id_or_email) || !isset($id_or_email->comment_ID)) {
            return $args;
        }

        if ($id_or_email->comment_type !== 'ai_comment') {
            $interact_type = get_comment_meta($id_or_email->comment_ID, '_ai_interact_type', true);
            // 包含评论官/智能回评/随手一评
            $is_interact_comment = in_array($interact_type, ['moderator', 'reply', 'autoreply', 'randcomment'], true);
            if (!$is_interact_comment) {
                return $args;
            }
        }

        if ($id_or_email->user_id) {
            $userAvatar = $this->get_avatar_by_user($id_or_email->user_id);
            if ($userAvatar) {
                $args['url'] = esc_url($userAvatar);
                $args['aiavatarurl'] = $args['url'];
            }
            return $args;
        }

        $comment_ID = $id_or_email->comment_ID;
        $ai_avatar = $this->get_ai_avatar($comment_ID);
        if ($ai_avatar) {
            $args['url'] = esc_url($ai_avatar);
            $args['aiavatarurl'] = $args['url'];
        }
        return $args;
    }

    public function filter_avatar_data($args, $id_or_email)
    {
        if (isset($args['aiavatarurl'])) {
            $args['url'] = $args['aiavatarurl'];
        }
        return $args;
    }

    /**
     * 修改原生评论类型下拉框
     */
    public function add_comment_types_dropdown($comment_types)
    {
        $comment_types['ai_comment'] = __('AI Comments', 'xhtheme-ai-toolbox');
        return $comment_types;
    }

    /**
     * 添加自定义列到评论列表
     */
    public function add_comment_columns($columns)
    {
        $new_columns = array();

        // 在评论内容列后添加来源列
        foreach ($columns as $key => $value) {
            $new_columns[$key] = $value;
            if ($key === 'comment') {
                $new_columns['comment_source'] = __('Source', 'xhtheme-ai-toolbox');
                $new_columns['comment_status'] = __('Status', 'xhtheme-ai-toolbox');
            }
        }

        return $new_columns;
    }

    /**
     * 显示自定义列内容
     */
    public function manage_comment_columns($column, $comment_id)
    {
        $comment = get_comment($comment_id);
        if (!$comment || !is_a($comment, 'WP_Comment')) {
            return;
        }
        if ($column === 'comment_source') {
            $comment_type = $comment->comment_type;
            $is_ai = $comment_type === 'ai_comment';
            $interact_type = get_comment_meta($comment_id, '_ai_interact_type', true);
            $is_interact = in_array($interact_type, ['moderator', 'reply', 'autoreply', 'randcomment'], true);
            echo '<p style="padding-top:5px;padding-bottom:5px">';
            if ($is_ai) {
                if ($comment->user_id > 0) {
                    $profile_url = get_edit_user_link($comment->user_id);
                    echo '<a href="' . esc_url($profile_url) . '" class="ai-user-badge" style="margin-top:5px;display:inline-block;background-color: #e5f7ff; color: #049be0; padding: 3px 8px; border-radius: 3px; font-size: 12px; text-decoration: none;" title="' . esc_attr__('User Profile', 'xhtheme-ai-toolbox') . '">' . esc_html__('AI User', 'xhtheme-ai-toolbox') . '</a>';
                } elseif ($comment->comment_approved == 0 && xh_option('commentuser', 'guest') !== 'guest') {
                    // 检查是否已在 insertComment 中确定为游客
                    if (get_comment_meta($comment_id, '_ai_guest_lock', true)) {
                        echo '<span class="ai-guest-badge" style="margin-top:5px;background-color: #e5f7e5; color: #00a32a; padding: 3px 8px; border-radius: 3px; font-size: 12px;">' . esc_html__('AI Guest', 'xhtheme-ai-toolbox') . '</span>';
                    } elseif (xh_option('commentuser', 'guest') === 'mixed') {
                        echo '<span class="ai-user-badge" style="margin-top:5px;background-color:rgb(255, 229, 254); color:rgb(224, 4, 154); padding: 3px 8px; border-radius: 3px; font-size: 12px;">' . esc_html__('AI Comments - Mixed Mode', 'xhtheme-ai-toolbox') . '</span>';
                        echo '<span style="display:flex;margin-top:4px;font-size:11px;line-height:1.4;color:#8c8f94;align-items: center;">';
                        echo '<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" style="vertical-align:middle;margin-right:4px;" xmlns="http://www.w3.org/2000/svg"><path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/></svg>';
                        echo esc_html__('Comment type is determined after publication', 'xhtheme-ai-toolbox');
                        echo '</span>';
                    } else {
                        echo '<span class="ai-user-badge" style="margin-top:5px;background-color: #ebffe5; color:rgb(4, 224, 173); padding: 3px 8px; border-radius: 3px; font-size: 12px;">' . esc_html__('AI User', 'xhtheme-ai-toolbox') . '</span>';
                        echo '<span style="display:flex;margin-top:4px;font-size:11px;line-height:1.4;color:#8c8f94;align-items: center;">';
                        echo '<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" style="vertical-align:middle;margin-right:4px;" xmlns="http://www.w3.org/2000/svg"><path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/></svg>';
                        echo esc_html__('Automatically generate users when publishing', 'xhtheme-ai-toolbox');
                        echo '</span>';
                    }
                } else {
                    echo '<span class="ai-guest-badge" style="margin-top:5px;background-color: #e5f7e5; color: #00a32a; padding: 3px 8px; border-radius: 3px; font-size: 12px;">' . esc_html__('AI Guest', 'xhtheme-ai-toolbox') . '</span>';
                }
            } elseif ($is_interact) {
                // AI 评论助手处理的评论，区分游客/用户
                if ($comment->user_id > 0) {
                    $profile_url = get_edit_user_link($comment->user_id);
                    echo '<a href="' . esc_url($profile_url) . '" class="ai-interact-badge" style="margin-top:5px;display:inline-block;background-color: #ede9fe; color: #7c3aed; padding: 3px 8px; border-radius: 3px; font-size: 12px; text-decoration: none;" title="' . esc_attr__('User Profile', 'xhtheme-ai-toolbox') . '">' . esc_html__('AI Assistant: User', 'xhtheme-ai-toolbox') . '</a>';
                } else {
                    echo '<span class="ai-interact-badge" style="margin-top:5px;background-color: #ede9fe; color: #7c3aed; padding: 3px 8px; border-radius: 3px; font-size: 12px;">' . esc_html__('AI Assistant: Guest', 'xhtheme-ai-toolbox') . '</span>';
                }
            } else {
                echo '<span class="user-badge" style="margin-top:5px;background-color: #f0f0f1; color: #50575e; padding: 3px 8px; border-radius: 3px; font-size: 12px;">' . esc_html__('User', 'xhtheme-ai-toolbox') . '</span>';
            }
            echo '</p>';
        }
        if ($column === 'comment_status') {
            echo '<p style="padding-top:5px;padding-bottom:5px">';
            $interact_type = get_comment_meta($comment_id, '_ai_interact_type', true);
            if ($comment->comment_approved == 0 && ($comment->comment_type === 'ai_comment' || $interact_type === 'reply')) {
                echo '<span style="color: #ff9800;">';
                /* translators: %s: Scheduled date and time in Y-m-d H:i format */
                echo sprintf(esc_html__('Schedule [%s]', 'xhtheme-ai-toolbox'), esc_html(mysql2date('Y-m-d H:i', $comment->comment_date)));
                echo '</span>';
            } else {
                $comment_type = get_comment_type($comment_id);
                $status = wp_get_comment_status($comment_id);
                $statuses = get_comment_statuses();
                switch ($status) {
                    case 'approved':
                        $status = 'approve';
                        break;
                    case 'unapproved':
                        $status = 'hold';
                        break;
                }
                if (isset($statuses[$status])) {
                    echo esc_html($statuses[$status]);
                } else {
                    echo esc_html($status);
                }
            }
            echo '</p>';
        }
    }

    public function add_comment_class($classes, $css_class, $comment_id, $comment, $post)
    {
        if ($comment && $comment->comment_type === 'ai_comment') {
            $classes[] = 'comment';
        }
        return $classes;
    }

    function add_comment_type($args)
    {
        if (isset($args['type']) && $args['type'] == 'comment') {
            $args['type'] = 'all';
        }
        return $args;
    }

    public function comment_notification($emails, $comment_id)
    {
        $commentNotice = xh_option('commentNotice', false);
        if (!$commentNotice) {
            return $emails;
        }
        $comment = get_comment($comment_id);
        if ($comment && $comment->comment_type === 'ai_comment') {
            return array();
        }
        return $emails;
    }

    /**
     * 过滤收件人列表，剔除 xmail.com 邮箱
     */
    public function filter_xmail_recipients($atts)
    {
        if (isset($atts['to'])) {
            $to = $atts['to'];
            if (!is_array($to)) {
                $to = explode(',', $to);
            }

            $new_to = array();
            foreach ($to as $email) {
                if (strpos(trim($email), '@xmail.com') === false) {
                    $new_to[] = trim($email);
                }
            }
            $atts['to'] = $new_to;
        }
        return $atts;
    }

    /**
     * 拦截发送给 xmail.com 的邮件
     */
    public function prevent_xmail_sending($return, $atts)
    {
        if (empty($atts['to'])) {
            return true;
        }
        $to = $atts['to'];
        if (is_array($to)) {
            foreach ($to as $email) {
                if (strpos($email, '@xmail.com') !== false) {
                    return true;
                }
            }
        } elseif (is_string($to) && strpos($to, '@xmail.com') !== false) {
            return true;
        }

        return $return;
    }

    /**
     * 处理头像本地化错误
     */
    public function avatarloacal_error($avatar_url)
    {
        $avatar_localerror = get_option('xhtheme_ai_toolbox_avatarlocal_error');
        $avatar_localerror = $avatar_localerror ? json_decode($avatar_localerror, true) : [];
        $daykeys = wp_date('Ymd');
        $avatar_localerror[$daykeys][] = $avatar_url;
        $sendEmail = false;
        if (count($avatar_localerror[$daykeys]) > 10) {
            $sendEmail = $avatar_localerror[$daykeys];
            unset($avatar_localerror[$daykeys]);
        }
        update_option('xhtheme_ai_toolbox_avatarlocal_error', json_encode($avatar_localerror));
        /**
         * 头像本地化失败过多，给管理员发送邮件
         */
        if ($sendEmail) {
            $admin_email = get_option('admin_email');
            if ($admin_email) {
                $notify_message = __('Dear Website Administrator:', 'xhtheme-ai-toolbox') . "\r\n";
                $notify_message .= __('The system has detected multiple failures in avatar localization (more than 10 times today). This may cause some comments to fail to display custom avatars.', 'xhtheme-ai-toolbox') . "\r\n\r\n";
                $notify_message .= __('Possible reasons:', 'xhtheme-ai-toolbox') . "\r\n";
                $notify_message .= __('1. Insufficient upload directory permissions', 'xhtheme-ai-toolbox') . "\r\n";
                $notify_message .= __('2. Remote image server downtime', 'xhtheme-ai-toolbox') . "\r\n";
                $notify_message .= __('3. Network connection issues', 'xhtheme-ai-toolbox') . "\r\n\r\n";
                $notify_message .= __('Recommended checks:', 'xhtheme-ai-toolbox') . "\r\n";
                $notify_message .= __('1. Ensure /wp-content/uploads/avatars directory is writable', 'xhtheme-ai-toolbox') . "\r\n";
                $notify_message .= __('2. Check error logs for details', 'xhtheme-ai-toolbox') . "\r\n";
                $notify_message .= __('3. Contact "Xinghe AI Toolbox" author for help. Website: https://www.xhtheme.com', 'xhtheme-ai-toolbox') . "\r\n\r\n\r\n";
                $notify_message .= __('This email was automatically sent by "Xinghe AI Toolbox" plugin!', 'xhtheme-ai-toolbox');
                wp_mail(
                    $admin_email,
                    __('Avatar Localization Failure Notification', 'xhtheme-ai-toolbox'),
                    $notify_message
                );
            }
        }
    }

    /**
     * 处理定时发布的评论
     * 支持 AI 自动评论(ai_comment) 和 AI 智能回评(comment) 两种类型
     */
    public function process_comment_status()
    {
        $current_time = current_time('mysql');
        $base_args = [
            'status' => 'hold',
            'date_query' => ['before' => $current_time],
            'number' => 50
        ];
        $ai_comments = get_comments(array_merge($base_args, [
            'type' => 'ai_comment'
        ]));

        $reply_comments = get_comments(array_merge($base_args, [
            'type' => 'comment',
            'meta_key' => '_ai_interact_type',
            'meta_value' => 'reply'
        ]));
        $comments = array_merge($ai_comments ?: [], $reply_comments ?: []);
        foreach ($comments as $comment) {
            wp_set_comment_status($comment->comment_ID, 'approve');
        }
    }

    public function process_ai_comments($cronArr)
    {
        if (!isset($cronArr['post_id']) || !isset($cronArr['data']['allnumber'])) {
            $cronArr['status'] = 'error';
            $cronArr['message'] = esc_html__('Parameter missing!', 'xhtheme-ai-toolbox');
            return $cronArr;
        }

        if (!isset($cronArr['data']['maxday']) || !isset($cronArr['data']['times'])) {
            $cronArr['status'] = 'error';
            $cronArr['message'] = esc_html__('Function changed, please delete the task!', 'xhtheme-ai-toolbox');
            return $cronArr;
        }

        $postId = $cronArr['post_id'];
        $post = get_post($postId);
        if (!$post) {
            $cronArr['status'] = 'error';
            $cronArr['message'] = esc_html__('No article found.', 'xhtheme-ai-toolbox');
            return $cronArr;
        }
        $comments = $this->get_postComments($postId);

        // 判断评论数量
        $existing_comments_count = count($comments);
        if ($existing_comments_count >= $this->maxComments) {
            $cronArr['status'] = 'success';
            return $cronArr;
        }

        /**
         * 组装请求参数
         */
        $allnumber = $cronArr['data']['allnumber'];
        $times = (array) $cronArr['data']['times'];

        $apiArgs = [
            'number' => $allnumber > 15 ? 10 : $allnumber,
            'exist' => [],
            'reply' => 0
        ];

        // 判断是否需要云端生成用户信息（昵称/头像）
        $commentuser = xh_option('commentuser', 'guest');
        $need_userinfo = 1;
        if ($commentuser === 'user') {
            $ai_user_limit = (int) xh_option('aiUserLimit', 200);
            if ($this->get_ai_user_count() >= $ai_user_limit) {
                $need_userinfo = 0;
            }
        }
        $apiArgs['addaiuser'] = $need_userinfo;
        if ($existing_comments_count > 4) {
            $apiArgs['reply'] = 1;
        }

        if ($existing_comments_count > 0) {
            foreach ($comments as $comment) {
                $apiArgs['exist'][] = [
                    'content' => $comment['content'],
                    'id' => $comment['id'],
                    'reply' => $comment['reply']
                ];
            }
        }

        // 使用统一 API 请求函数
        $result = xh_api_request('post-comment', ['args' => $apiArgs], $post);

        if (is_wp_error($result)) {
            return xh_api_handle_error($result, $cronArr, '[XHComment]');
        }

        $newComments = $result;
        if (!$newComments || !is_array($newComments)) {
            return $cronArr;
        }

        foreach ($newComments as $key => $comment) {
            if (isset($times[$key])) {
                $newComments[$key]['date'] = $times[$key];
                unset($times[$key]);
            } else {
                $newComments[$key]['date'] = current_time('mysql');
            }
        }
        $times = array_values($times);

        $passNumber = $this->analysisComment($postId, $newComments, $comments);
        if ($allnumber - $passNumber > 2) {
            $cronArr['status'] = 'hold';
            $cronArr['data']['allnumber'] = $allnumber - $passNumber;
            $cronArr['data']['times'] = $times;
        } else {
            $cronArr['status'] = 'success';
        }

        return $cronArr;
    }

    public function analysisComment($postId, $newComments, $comments = [])
    {

        $number = 0;

        if (apply_filters('xhtheme_ai_toolbox_pre_comments_publish', false)) {
            return apply_filters('xhtheme_ai_toolbox_comments_publish', $number, $newComments, $comments);
        }

        $existingContents = [];
        // 提取已存在评论的内容与时间戳
        foreach ($comments as $comment) {
            $existingContents[] = trim($comment['content']);
        }

        $validComments = [];

        foreach ($newComments as $comment) {
            if (empty($comment['content'])) {
                continue;
            }

            $content = trim($comment['content']);
            if (in_array($content, $existingContents)) {
                continue;
            }

            $existingContents[] = $content;
            $validComments[] = $comment;
        }

        foreach ($validComments as $comment) {
            $comment['date_gmt'] = get_gmt_from_date($comment['date']);
            if ($this->insertComment($postId, $comment)) {
                $number++;
            }
        }

        return $number;
    }

    /**
     * 获取评论
     * @param int $postId 文章ID
     * @return array 评论数据
     */
    public function get_postComments($postId)
    {
        $comments_query = get_comments(array(
            'post_id' => $postId,
            'status' => array('approve', 'hold'),
            'hierarchical' => 'threaded',
            'order' => 'ASC'
        ));

        $processed_comments = [];

        // 首先收集所有子评论信息
        $comment_children = [];
        foreach ($comments_query as $comment) {
            if ($comment->comment_parent > 0) {
                if (!isset($comment_children[$comment->comment_parent])) {
                    $comment_children[$comment->comment_parent] = 1;
                }
            }
        }

        // 处理每条评论
        foreach ($comments_query as $comment) {
            // 获取头像信息
            $avatar = get_comment_meta($comment->comment_ID, '_ai_avatar', true) ?: '';
            if ($comment->comment_parent > 0) {
                continue;
            }
            // 构建评论数据
            $processed_comment = array(
                'id' => $comment->comment_ID,
                'username' => $comment->comment_author,
                'content' => $comment->comment_content,
                'date' => $comment->comment_date,
                'avatar' => $avatar,
                'reply' => isset($comment_children[$comment->comment_ID]) ? 0 : 1
            );
            $processed_comments[] = $processed_comment;
        }

        return $processed_comments;
    }

    public function get_ai_avatar($comment_ID)
    {
        $avatar = get_comment_meta($comment_ID, '_ai_avatar', true);
        if (empty($avatar)) {
            return '';
        }

        if (filter_var($avatar, FILTER_VALIDATE_URL)) {
            return $avatar;
        }

        $avatar_url = xh_parse_avatar($avatar);
        if (!$avatar_url) {
            delete_comment_meta($comment_ID, '_ai_avatar');
            return '';
        }
        $avatar_url = esc_url($avatar_url);
        update_comment_meta($comment_ID, '_ai_avatar', $avatar_url);
        return $avatar_url;
    }

    /**
     * 根据用户id获取头像
     */
    public function get_avatar_by_user($user_id)
    {
        if (empty($user_id)) {
            return '';
        }
        $user_avatar = get_user_meta($user_id, '_ai_avatar', true);
        if ($user_avatar) {
            return $user_avatar;
        }
        return '';
    }

    /**
     * 输出一条随机评论的信息
     */
    public function get_random_comment_optimized($current_post_id)
    {
        global $wpdb;
        static $commentallCount = null;
        static $commentallId = null;
        if ($commentallId === null || $commentallId != $current_post_id) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Cached in static variable
            $commentallCount = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(comment_ID) FROM $wpdb->comments
                 WHERE comment_type = %s AND comment_post_ID != %d",
                'ai_comment',
                $current_post_id
            ));
            $commentallId = $current_post_id;
        }

        if (empty($commentallCount)) {
            return null;
        }

        // 生成一个随机偏移量
        $random_offset = wp_rand(0, $commentallCount - 1);

        // 根据随机偏移量获取一条评论
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Random query not cacheable
        $random_comment = $wpdb->get_row($wpdb->prepare(
            "SELECT comment_ID, comment_author_email, comment_agent, comment_author
             FROM $wpdb->comments
             WHERE comment_type = %s AND comment_post_ID != %d
             LIMIT %d, 1",
            'ai_comment',
            $current_post_id,
            $random_offset
        ), ARRAY_A);

        return $random_comment;
    }

    /**
     * 评论昵称处理
     */
    public function commentNameFilter($comment)
    {
        global $wpdb;
        $username = $comment['comment_author'];
        $current_post_id = $comment['comment_post_ID'];

        $use_random_comment = true;

        if (!empty($username)) {
            $use_random_comment = false;
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-time lookup for comment author
            $existing_comments = $wpdb->get_results($wpdb->prepare(
                "SELECT comment_ID, comment_author_email, comment_agent, comment_post_ID, comment_author
                FROM $wpdb->comments
                WHERE comment_type = %s AND comment_author = %s
                ORDER BY comment_ID DESC
                LIMIT 30",
                'ai_comment',
                $username
            ), ARRAY_A);

            if (!empty($existing_comments)) {
                foreach ($existing_comments as $exist_comment) {
                    if ((int) $exist_comment['comment_post_ID'] === (int) $current_post_id) {
                        $use_random_comment = true;
                        break;
                    }
                }

                if (!$use_random_comment) {
                    $first_exist_comment = $existing_comments[0];
                    $comment['comment_author'] = $first_exist_comment['comment_author'];
                    $comment['comment_author_email'] = $first_exist_comment['comment_author_email'];
                    $comment['comment_agent'] = $first_exist_comment['comment_agent'];
                    $comment['avatar'] = get_comment_meta($first_exist_comment['comment_ID'], '_ai_avatar', true);
                }
            }
        }

        if ($use_random_comment) {
            // 使用优化后的随机评论获取函数
            $random_comment = $this->get_random_comment_optimized($current_post_id);
            if ($random_comment) {
                $comment['comment_author'] = $random_comment['comment_author'];
                $comment['comment_author_email'] = $random_comment['comment_author_email'];
                $comment['comment_agent'] = $random_comment['comment_agent'];
                if (isset($random_comment['comment_ID'])) {
                    $comment['avatar'] = get_comment_meta($random_comment['comment_ID'], '_ai_avatar', true);
                }
            } else {
                $max_attempts = 5; // 设置最大尝试次数
                $attempt = 0;
                $nickname_used = true;

                while ($nickname_used && $attempt < $max_attempts) {
                    $random_nickname = $this->get_rand_nicknames();
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Loop check for nickname uniqueness
                    $existing_nickname = $wpdb->get_var(
                        $wpdb->prepare(
                            "SELECT comment_ID FROM $wpdb->comments 
                            WHERE comment_post_ID = %d 
                            AND comment_author = %s 
                            LIMIT 1",
                            $current_post_id,
                            $random_nickname
                        )
                    );

                    if (!$existing_nickname) {
                        $nickname_used = false;
                        $comment['comment_author'] = $random_nickname;
                    }

                    $attempt++;
                }

                if ($nickname_used) {
                    $comment['comment_author'] = __('Guest', 'xhtheme-ai-toolbox') . wp_rand(100, 999);
                }
            }
        }
        return $comment;
    }

    /**
     * 创建单个AI评论
     * @param int $postId 文章ID
     * @param array $comment 评论数据
     * @return int|false 成功返回评论ID，失败返回false
     */
    public function insertComment($postId, $comment)
    {
        // 准备评论数据
        $commentdata = array(
            'comment_post_ID' => $postId,
            'comment_author' => isset($comment['username']) ? $comment['username'] : '',
            'comment_author_email' => $this->generateRandomEmail(),
            'comment_content' => $comment['content'],
            'comment_type' => 'ai_comment',
            'comment_approved' => 0,
            'comment_author_IP' => isset($comment['ip']) ? $comment['ip'] : $this->getRandomIP(),
            'comment_agent' => $this->getAgents(),
            'comment_date' => isset($comment['date']) ? $comment['date'] : current_time('mysql'),
            'comment_parent' => isset($comment['parent']) ? (int) $comment['parent'] : 0
        );
        if (isset($comment['date_gmt'])) {
            $commentdata['comment_date_gmt'] = $comment['date_gmt'];
        } else {
            $commentdata['comment_date_gmt'] = get_gmt_from_date($commentdata['comment_date']);
        }
        /**
         * 处理昵称重复问题
         */
        $commentdata = $this->commentNameFilter($commentdata);

        /**
         * 插入时绑定 AI 用户
         */
        $commentuser = xh_option('commentuser', 'guest');
        $skip_ai_bind = false;
        if ($commentuser === 'mixed') {
            $commentMixedRatio = xh_option('commentMixedRatio', 20);
            if (wp_rand(1, 100) < $commentMixedRatio) {
                $skip_ai_bind = true; // 此评论保持游客身份
            }
        }
        if ($commentuser === 'user' || ($commentuser === 'mixed' && !$skip_ai_bind)) {
            $ai_user_limit = (int) xh_option('aiUserLimit', 200);
            $ai_user = null;
            if ($this->get_ai_user_count() < $ai_user_limit) {
                $ai_user = $this->create_ai_user([
                    'name'   => $commentdata['comment_author'],
                    'avatar' => isset($comment['avatar']) ? $comment['avatar'] : ''
                ]);
            } else {
                $ai_user = $this->get_random_aiuser($postId);
            }
            if ($ai_user) {
                $commentdata['user_id'] = $ai_user->ID;
                $commentdata['comment_author'] = $ai_user->display_name;
                $commentdata['comment_author_email'] = $ai_user->user_email;
            }
        }

        // 插入评论
        $comment_id = wp_insert_comment($commentdata);
        if ($comment_id) {
            if (empty($commentdata['user_id'])) {
                add_comment_meta($comment_id, '_ai_avatar', wp_json_encode($comment['avatar']), true);
                if ($skip_ai_bind) {
                    add_comment_meta($comment_id, '_ai_guest_lock', 1, true);
                }
            }
            // 根据文章评论数量来决定评论发布时间
            $comment_count = wp_count_comments($postId);
            if ($comment_count->approved == 0) {
                if (
                    wp_update_comment([
                        'comment_ID' => $comment_id,
                        'comment_date' => current_time('mysql')
                    ])
                ) {
                    wp_set_comment_status($comment_id, 'approve');
                }
            }
            do_action('xhaitoolbox_comment_created', $comment_id);
            return $comment_id;
        }

        return false;
    }


    function pushComment($postId, $comments, $allnumber = 0, $maxdays = 1)
    {
        // 添加评论
        if (!$comments || !is_array($comments) || !$postId) {
            return;
        }
        $numbers = $allnumber > count($comments) ? $allnumber : count($comments);
        $inserted_comments = array();

        $comentCount = count($comments);
        $times = xh_randTimeList('', $maxdays, $numbers + $comentCount);
        foreach ($comments as $key => $comment) {
            $comments[$key]['date'] = $times[$key];
            unset($times[$key]);
        }
        $times = array_values($times);

        $this->analysisComment($postId, $comments, []);

        if ($numbers > 0) {
            /**
             *预留定时任务
             */
            $Cronrow = xh_cron_getrow('comment' . '_' . $postId);
            if (!$Cronrow) {
                xh_cron_insert($postId, 'comment', [
                    'maxday' => $maxdays,
                    'allnumber' => $numbers,
                    'times' => $times
                ]);
            }
        }
        return $inserted_comments;
    }
}
