<?php

namespace XHTheme\AIToolbox;

defined('ABSPATH') || exit;

class XHTool
{

    /**
     * 随机邮箱生成
     */
    public function generateRandomEmail($prefix = '')
    {
        $domains = apply_filters('xhaitoolbox_randomemail_domains', ['xmail.com']);
        $domain = $domains[array_rand($domains)];
        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
        $random_str = '';
        for ($i = 0; $i < 8; $i++) {
            $random_str .= $chars[wp_rand(0, strlen($chars) - 1)];
        }
        return $prefix . $random_str . '@' . $domain;
    }

    public function getAgents()
    {
        $user_agents = array(
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Safari/605.1.15',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.69',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/117.0',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
            'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
            'Mozilla/5.0 (iPad; CPU OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 OPR/102.0.0.0',
            'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko',
            'Mozilla/5.0 (Android 13; Mobile; rv:109.0) Gecko/116.0 Firefox/116.0',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/116.0',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Vivaldi/6.1.3035.111',
            'Mozilla/5.0 (Linux; Android 13; SM-S908B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36',
            'Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36',
            'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Safari Line/13.5.0',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.62',
            'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/116.0',
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Whale/3.21.192.18',
            'Mozilla/5.0 (Linux; Android 13; SM-A536B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36'
        );

        // 随机返回一个浏览器 User-Agent
        return $user_agents[array_rand($user_agents)];
    }

    /**
     * 生成随机 IP 地址
     */
    public function getRandomIP()
    {
        // 避免生成保留 IP 段（0.x.x.x, 10.x.x.x, 127.x.x.x, 172.16-31.x.x, 192.168.x.x 等）
        do {
            $first = wp_rand(1, 223);
        } while (in_array($first, [0, 10, 127], true));

        // 避免 172.16.0.0 - 172.31.255.255 和 192.168.x.x
        $second = wp_rand(0, 255);
        if ($first === 172 && $second >= 16 && $second <= 31) {
            $second = wp_rand(0, 15);
        }
        if ($first === 192 && $second === 168) {
            $second = wp_rand(0, 167);
        }

        return sprintf('%d.%d.%d.%d', $first, $second, wp_rand(0, 255), wp_rand(1, 254));
    }

    /**
     * 获取用户固定 IP 地址
     * 从历史评论中获取，如果无历史评论则返回随机IP
     * 
     * @param int $user_id 用户ID
     * @return string IP地址
     */
    public function getUserIP($user_id)
    {
        if (!$user_id) {
            return $this->getRandomIP();
        }

        $comment = $this->getUserLastComment($user_id);
        if ($comment && !empty($comment->comment_author_IP)) {
            return $comment->comment_author_IP;
        }

        return $this->getRandomIP();
    }

    /**
     * 获取用户固定 User-Agent
     * 从历史评论中获取，如果无历史评论则返回随机Agent
     * 
     * @param int $user_id 用户ID
     * @return string User-Agent
     */
    public function getUserAgent($user_id)
    {
        if (!$user_id) {
            return $this->getAgents();
        }

        $comment = $this->getUserLastComment($user_id);
        if ($comment && !empty($comment->comment_agent)) {
            return $comment->comment_agent;
        }

        return $this->getAgents();
    }

    /**
     * 获取用户最近一条评论（带缓存）
     * 
     * @param int $user_id 用户ID
     * @return WP_Comment|null
     */
    protected function getUserLastComment($user_id)
    {
        static $cache = [];

        if (isset($cache[$user_id])) {
            return $cache[$user_id];
        }

        $comments = get_comments([
            'user_id' => $user_id,
            'number' => 1,
            'orderby' => 'comment_date',
            'order' => 'DESC',
            'status' => 'all'
        ]);

        $cache[$user_id] = !empty($comments) ? $comments[0] : null;
        return $cache[$user_id];
    }

    /**
     * 预设昵称
     */
    public function get_rand_nicknames()
    {
        $nicknames = [
            __('Starlight', 'xhtheme-ai-toolbox'),
            __('Windwalker', 'xhtheme-ai-toolbox'),
            __('Shadow', 'xhtheme-ai-toolbox'),
            __('Dreamer', 'xhtheme-ai-toolbox'),
            __('Aurora', 'xhtheme-ai-toolbox'),
            __('Fawn', 'xhtheme-ai-toolbox'),
            __('Nightwhisper', 'xhtheme-ai-toolbox'),
            __('Phantom', 'xhtheme-ai-toolbox'),
            __('Breeze', 'xhtheme-ai-toolbox'),
            __('Future', 'xhtheme-ai-toolbox'),
            __('Smile', 'xhtheme-ai-toolbox'),
            __('Passion', 'xhtheme-ai-toolbox'),
            __('Silence', 'xhtheme-ai-toolbox'),
            __('Lightyear', 'xhtheme-ai-toolbox'),
            __('Trend', 'xhtheme-ai-toolbox'),
            __('Lone Wolf', 'xhtheme-ai-toolbox'),
            __('Cloud', 'xhtheme-ai-toolbox'),
            __('Hope', 'xhtheme-ai-toolbox'),
            __('Spark', 'xhtheme-ai-toolbox'),
            __('Dawn', 'xhtheme-ai-toolbox'),
        ];
        return $nicknames[array_rand($nicknames)];
    }

    /**
     * 检测是否为索引数组
     */
    protected function is_indexed_array($arr)
    {
        if (!is_array($arr) || empty($arr)) {
            return false;
        }
        return array_keys($arr) === range(0, count($arr) - 1);
    }

    /**
     * 根据 API 返回的用户数据创建 AI 用户
     */
    public function create_ai_user($user_data)
    {
        $name = $user_data['name'] ?? '';
        if (empty($name)) {
            return null;
        }
        $max_attempts = 10;
        $attempt = 0;
        do {
            $user_login = substr(md5(uniqid(wp_rand(), true)), 0, 8);
            $attempt++;
        } while (username_exists('xhai_' . $user_login) && $attempt < $max_attempts);

        $email = $user_login . '@xmail.com';
        $newuser = [
            'user_login'   => 'xhai_' . $user_login,
            'user_email'   => $email,
            'display_name' => $name,
            'nickname'     => $name,
            'user_pass'    => wp_generate_password(16),
            'role'         => 'xhaiuser'
        ];
        if (!empty($user_data['avatar'])) {
            $avatar = xh_parse_avatar($user_data['avatar']);
            if ($avatar) {
                $newuser['meta_input']['_ai_avatar'] = $avatar;
            }
        }
        $user_id = wp_insert_user($newuser);

        if (is_wp_error($user_id)) {
            return null;
        }
        return get_userdata($user_id);
    }

    /**
     * 获取随机 AI 用户
     * 
     * @param int|null $exclude_post_id 排除在此文章评论过的用户，null 则不排除
     * @return WP_User|null
     */
    public function get_random_aiuser($exclude_post_id = null)
    {
        global $wpdb;
        $cache_key = 'xhinteract_aiuser_pool';
        $user_ids = get_transient($cache_key);
        $orderby_options = ['name', 'login', 'email', 'registered'];
        if ($user_ids === false) {
            $batch_size = 100;
            $total = $this->get_ai_user_count();

            if ($total <= $batch_size) {
                $offset = 0;
                $limit = $total;
            } else {
                $max_offset = $total - $batch_size;
                $offset = wp_rand(0, $max_offset);
                $limit = $batch_size;
            }

            $orderby = $orderby_options[array_rand($orderby_options)];
            $users = get_users([
                'role' => 'xhaiuser',
                'fields' => 'ID',
                'number' => $limit,
                'offset' => $offset,
                'orderby' => $orderby,
                'cache_results' => false
            ]);
            $user_ids = !empty($users) ? array_map('intval', $users) : [];
            set_transient($cache_key, $user_ids, DAY_IN_SECONDS);
        }

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

        $available_ids = $user_ids;
        if ($exclude_post_id) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $used_ids = $wpdb->get_col($wpdb->prepare(
                "SELECT DISTINCT user_id FROM {$wpdb->comments} 
                 WHERE comment_post_ID = %d AND user_id > 0",
                $exclude_post_id
            ));

            if (!empty($used_ids)) {
                $available_ids = array_diff($user_ids, array_map('intval', $used_ids));
                if (empty($available_ids)) {
                    $users = get_users([
                        'role' => 'xhaiuser',
                        'fields' => 'ID',
                        'orderby' => $orderby_options[array_rand($orderby_options)],
                        'number' => 10,
                        'exclude' => $used_ids,
                        'cache_results' => false
                    ]);
                    if (empty($users)) {
                        return null;
                    }
                    $random_id = $users[array_rand($users)];
                    return get_userdata($random_id);
                }
            }
        }

        $random_id = $available_ids[array_rand($available_ids)];

        $remaining_ids = array_values(array_diff($user_ids, [$random_id]));
        if (count($remaining_ids) < 5) {
            delete_transient($cache_key);
        } else {
            set_transient($cache_key, $remaining_ids, DAY_IN_SECONDS);
        }

        return get_userdata($random_id);
    }

    /**
     * 获取 AI 用户数量
     */
    public function get_ai_user_count()
    {
        $query = new \WP_User_Query([
            'role' => 'xhaiuser',
            'count_total' => true,
            'number' => 0,
            'fields' => 'ID'
        ]);
        return $query->get_total();
    }

    /**
     * 过滤评论昵称（确保同一文章内不重复）
     */
    public function filterCommentNickname($post_id, $nickname = '')
    {
        global $wpdb;
        if (!empty($nickname)) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $exists = $wpdb->get_var($wpdb->prepare(
                "SELECT comment_ID FROM {$wpdb->comments} 
                 WHERE comment_post_ID = %d AND comment_author = %s LIMIT 1",
                $post_id,
                $nickname
            ));

            if (!$exists) {
                return [
                    'name' => $nickname,
                    'email' => $this->generateRandomEmail(),
                    'agent' => $this->getAgents()
                ];
            }
        }
        $max_attempts = 5;
        for ($i = 0; $i < $max_attempts; $i++) {
            $random_name = $this->get_rand_nicknames();
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $exists = $wpdb->get_var($wpdb->prepare(
                "SELECT comment_ID FROM {$wpdb->comments} 
                 WHERE comment_post_ID = %d AND comment_author = %s LIMIT 1",
                $post_id,
                $random_name
            ));

            if (!$exists) {
                return [
                    'name' => $random_name,
                    'email' => $this->generateRandomEmail(),
                    'agent' => $this->getAgents()
                ];
            }
        }

        // 都失败则用随机后缀
        return [
            'name' => __('Guest', 'xhtheme-ai-toolbox') . wp_rand(100, 999),
            'email' => $this->generateRandomEmail(),
            'agent' => $this->getAgents()
        ];
    }
}
