<?php

namespace XHTheme\AIToolbox;

defined('ABSPATH') || exit;

function xh_option($name, $default = '', $cache = true)
{
    $xhoptions_data = get_option('xhtheme_ai_toolbox_settings', []);
    if (isset($xhoptions_data[$name])) {
        return $xhoptions_data[$name];
    }
    return $default;
}

function xh_setoption($name, $value)
{
    $options = get_option('xhtheme_ai_toolbox_settings', []);
    $options = is_array($options) ? $options : [];
    $options[$name] = $value;
    update_option('xhtheme_ai_toolbox_settings', $options);
}

function xh_automation_task_feature_map()
{
    return apply_filters('xhaitoolbox_automation_task_feature_map', [
        'summary' => [
            'option' => 'summaryEnabled',
            'default' => true,
        ],
        'tags' => [
            'option' => 'tagEnabled',
            'default' => true,
        ],
        'comments' => [
            'option' => 'commentEnabled',
            'default' => true,
        ],
        'slug' => [
            'option' => 'primarySlug',
            'default' => false,
        ],
        'category' => [
            'option' => 'primaryCategory',
            'default' => false,
        ],
        'thread' => [
            'option' => 'primaryThread',
            'default' => true,
        ],
        'aiimage' => [
            'option' => 'imageThumb',
            'default' => false,
        ],
    ]);
}

function xh_automation_task_capabilities()
{
    $capabilities = [];
    foreach (xh_automation_task_feature_map() as $task => $config) {
        $capabilities[$task] = [
            'enabled' => (bool) xh_option($config['option'], $config['default']),
            'option' => $config['option'],
            'reason' => __('This feature is turned off in Basic Settings. Enable it before using it in automation workflows.', 'xhtheme-ai-toolbox'),
        ];
    }
    return $capabilities;
}

function xh_automation_task_enabled($task)
{
    $capabilities = xh_automation_task_capabilities();
    return !isset($capabilities[$task]) || !empty($capabilities[$task]['enabled']);
}

function xh_cron_task_to_automation_task($type)
{
    $map = [
        'summary' => 'summary',
        'tags' => 'tags',
        'comment' => 'comments',
        'threadlist' => 'thread',
        'imageword' => 'aiimage',
    ];
    return isset($map[$type]) ? $map[$type] : $type;
}

/**
 * 获取本地时区时间戳 
 * @return int 本地时区的 Unix 时间戳
 */
function xh_local_timestamp()
{
    return strtotime(current_time('mysql'));
}

function xh_darkClass($subClass = '')
{
    $baseClasses = [
        '.dark',
        '[data-bs-theme=dark]',
        '.io-black-mode',
        '.style-for-dark',
        '.dark-theme',
        '#ceotheme.night',
        '.wp-theme-begin.night',
        '.puock-dark',
        '.nice-dark-mode'
    ];

    $darkClasses = apply_filters('xhaitoolbox_darkClass', $baseClasses);
    if (!is_array($darkClasses) || empty($darkClasses)) {
        return trim($subClass);
    }

    if (empty($subClass)) {
        return implode(', ', array_filter($darkClasses));
    }

    $result = [];
    foreach ($darkClasses as $class) {
        $class = trim($class);
        if (!empty($class)) {
            $result[] = $class . ' ' . trim($subClass);
        }
    }
    return implode(', ', $result);
}

function xh_postTypedata($type = '')
{
    $datas = [
        'post' => [
            'name' => __('WordPress Post', 'xhtheme-ai-toolbox'),
            'type' => 'wp',
            'typename' => __('WordPress', 'xhtheme-ai-toolbox'),
            'subname' => __('Post', 'xhtheme-ai-toolbox'),
            'slug' => 'post',
            'description' => __('Auto-generate summaries, English slugs, images, reviews, tags, and categories with ease.', 'xhtheme-ai-toolbox'),
            'tags' => 'post_tag',
            'categories' => 'category',
            'color' => 'sky',
            'autopublish' => [],
            'queue' => true,
            'tasks' => [
                'summary',
                'slug',
                'aiimage',
                'thread',
                'comments',
                'tags',
                'category'
            ]
        ],
        'shop' => [
            'name' => __('B2 Theme Shopping District', 'xhtheme-ai-toolbox'),
            'type' => 'theme',
            'typename' => __('B2 Theme', 'xhtheme-ai-toolbox'),
            'subname' => __('Product', 'xhtheme-ai-toolbox'),
            'slug' => 'product',
            'description' => __('B2 Theme-compatible business district models with auto-generated reviews, tags, English slugs, and categories.', 'xhtheme-ai-toolbox'),
            'tags' => 'post_tag',
            'categories' => 'shoptype',
            'color' => 'green',
            'autopublish' => [],
            'queue' => true,
            'tasks' => [
                'slug',
                'comments',
                'tags',
                'category'
            ]
        ],
        'community' => [
            'name' => __('GuaQi -> Community', 'xhtheme-ai-toolbox'),
            'type' => 'plugin',
            'typename' => __('GuaQi Plugin', 'xhtheme-ai-toolbox'),
            'subname' => __('Community', 'xhtheme-ai-toolbox'),
            'slug' => 'community',
            'description' => __('GuaQi community type can automatically generate comments, tags, and categories.', 'xhtheme-ai-toolbox'),
            'tags' => 'community_tag',
            'categories' => 'community_cat',
            'color' => 'purple',
            'autopublish' => [],
            'queue' => true,
            'tasks' => [
                'slug',
                'comments',
                'tags',
                'category'
            ]
        ],
        'product' => [
            'name' => __('Woocommerce Product', 'xhtheme-ai-toolbox'),
            'type' => 'plugin',
            'typename' => __('Woocommerce Plugin', 'xhtheme-ai-toolbox'),
            'subname' => __('Product', 'xhtheme-ai-toolbox'),
            'slug' => 'product',
            'description' => __('WooCommerce product models with auto-generated reviews, tags, and categories.', 'xhtheme-ai-toolbox'),
            'tags' => 'product_tag',
            'categories' => 'product_cat',
            'color' => 'purple',
            'autopublish' => [],
            'queue' => true,
            'tasks' => [
                'slug',
                'comments',
                'tags',
                'category'
            ]
        ],
        'sites' => [
            'name' => __('OneNav Theme Website', 'xhtheme-ai-toolbox'),
            'type' => 'theme',
            'typename' => __('OneNav Theme', 'xhtheme-ai-toolbox'),
            'subname' => __('Website', 'xhtheme-ai-toolbox'),
            'slug' => 'sites',
            'description' => __('OneNav-compatible site models with auto-generated reviews, tags, and categories.', 'xhtheme-ai-toolbox'),
            'tags' => 'sitetag',
            'categories' => 'favorites',
            'color' => 'orange',
            'autopublish' => [],
            'queue' => true,
            'tasks' => [
                'slug',
                'comments',
                'tags',
                'category'
            ]
        ],
        'app' => [
            'name' => __('OneNav Theme -> App/Resources', 'xhtheme-ai-toolbox'),
            'type' => 'theme',
            'typename' => __('OneNav Theme', 'xhtheme-ai-toolbox'),
            'subname' => __('App/Resources', 'xhtheme-ai-toolbox'),
            'slug' => 'app',
            'description' => __('OneNav Theme App/Resources model with automatic comments, topic generation, tags, and categories.', 'xhtheme-ai-toolbox'),
            'tags' => 'apptag',
            'categories' => 'apps',
            'color' => 'blue',
            'autopublish' => [],
            'queue' => true,
            'tasks' => [
                'slug',
                'comments',
                'thread',
                'tags',
                'category'
            ]
        ],
        'forum_post' => [
            'name' => __('Zibll Theme -> Community', 'xhtheme-ai-toolbox'),
            'type' => 'theme',
            'typename' => __('Zibll Theme', 'xhtheme-ai-toolbox'),
            'subname' => __('Community', 'xhtheme-ai-toolbox'),
            'slug' => 'community',
            'description' => __('Add AI capabilities to Zibll theme community posts.', 'xhtheme-ai-toolbox'),
            'tags' => 'forum_tag',
            'color' => 'orange',
            'autopublish' => [],
            'queue' => true,
            'tasks' => [
                'comments',
                'tags'
            ]
        ]
    ];

    /**
     * Filter the post type data.
     */
    $datas = apply_filters('xhaitoolbox_post_type_data', $datas, $type);

    if (!empty($type)) {
        return isset($datas[$type]) ? $datas[$type] : [];
    }
    return $datas;
}

/**
 * 获取标签列表供AI使用
 */
function xh_get_tags($post_type, $category_id = null, $max_tags = 200)
{
    $postTypedata = xh_postTypedata($post_type);
    if (empty($postTypedata) || !isset($postTypedata['tags'])) {
        return '';
    }

    $tags_taxonomy = $postTypedata['tags'];
    $categories_taxonomy = isset($postTypedata['categories']) ? $postTypedata['categories'] : '';
    $cache_key = 'xhtag_' . $post_type . '_' . ($category_id ? intval($category_id) : '0');
    $cached_tags = get_transient($cache_key);
    if ($cached_tags !== false) {
        return $cached_tags;
    }
    $total_tags = wp_count_terms(array(
        'taxonomy' => $tags_taxonomy,
        'hide_empty' => true,
    ));

    if (is_wp_error($total_tags)) {
        $total_tags = 0;
    }
    if (!$total_tags) {
        return '';
    }

    $tag_names = [];
    if ($total_tags < $max_tags) {
        $all_tags = get_terms(array(
            'taxonomy' => $tags_taxonomy,
            'hide_empty' => true,
            'orderby' => 'count',
            'order' => 'DESC'
        ));

        if (!is_wp_error($all_tags) && !empty($all_tags)) {
            foreach ($all_tags as $tag) {
                $tag_names[] = $tag->name;
            }
        }
    } else {
        if ($category_id && $categories_taxonomy) {
            $tag_names = xh_get_tags_by_category($post_type, $tags_taxonomy, $categories_taxonomy, $category_id, $max_tags);
        } else {
            $top_tags = get_terms(array(
                'taxonomy' => $tags_taxonomy,
                'hide_empty' => true,
                'orderby' => 'count',
                'order' => 'DESC',
                'number' => $max_tags
            ));

            if (!is_wp_error($top_tags) && !empty($top_tags)) {
                foreach ($top_tags as $tag) {
                    $tag_names[] = $tag->name;
                }
            }
        }
    }

    $result = implode(',', $tag_names);
    set_transient($cache_key, $result, DAY_IN_SECONDS);

    return $result;
}

/**
 * 增量更新标签缓存
 */
function xh_update_tags_cache($post_type, $category_id, $new_tags)
{
    if (empty($new_tags) || !is_array($new_tags)) {
        return;
    }

    $new_str = implode(',', $new_tags);
    $max_cache_length = 3000;

    $cache_key = 'xhtag_' . $post_type . '_' . ($category_id ? intval($category_id) : '0');
    $cached_tags = get_transient($cache_key);
    if ($cached_tags !== false) {
        if (strlen($cached_tags) > $max_cache_length) {
            delete_transient($cache_key);
        } else {
            $result = $cached_tags ? $cached_tags . ',' . $new_str : $new_str;
            set_transient($cache_key, $result, DAY_IN_SECONDS);
        }
    }

    if ($category_id) {
        $general_cache_key = 'xhtag_' . $post_type . '_0';
        $general_cached_tags = get_transient($general_cache_key);
        if ($general_cached_tags !== false) {
            if (strlen($general_cached_tags) > $max_cache_length) {
                delete_transient($general_cache_key);
            } else {
                $result = $general_cached_tags ? $general_cached_tags . ',' . $new_str : $new_str;
                set_transient($general_cache_key, $result, DAY_IN_SECONDS);
            }
        }
    }
}

/**
 * 根据分类获取相关标签名称
 */
function xh_get_tags_by_category($post_type, $tags_taxonomy, $categories_taxonomy, $category_id, $max_tags = 300)
{
    global $wpdb;

    $post_ids = get_posts(array(
        'post_type' => $post_type,
        'post_status' => 'publish',
        'posts_per_page' => 100,
        'fields' => 'ids',
        'tax_query' => array(
            array(
                'taxonomy' => $categories_taxonomy,
                'field' => 'term_id',
                'terms' => $category_id
            )
        )
    ));

    if (empty($post_ids)) {
        return [];
    }

    $placeholders = implode(',', array_fill(0, count($post_ids), '%d'));

    $tags_data = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT t.name, COUNT(tr.object_id) as post_count
            FROM {$wpdb->terms} t
            INNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
            INNER JOIN {$wpdb->term_relationships} tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
            WHERE tt.taxonomy = %s
            AND tr.object_id IN ($placeholders)
            GROUP BY t.term_id
            ORDER BY post_count DESC
            LIMIT %d",
            array_merge(
                array($tags_taxonomy),
                $post_ids,
                array($max_tags)
            )
        )
    );

    $tag_names = [];
    if (!empty($tags_data)) {
        foreach ($tags_data as $tag) {
            $tag_names[] = $tag->name;
        }
    }

    return $tag_names;
}

function xh_postTypes()
{
    $datas = xh_postTypedata();
    return array_keys($datas);
}


function xh_active_post_types()
{
    $post_types = get_post_types(array(
        'public' => true,
        '_builtin' => false
    ), 'names');
    if (!$post_types) {
        $post_types = [];
    }
    $post_types = array_keys($post_types);
    $post_types = array_merge(['post'], $post_types);
    $datas = xh_postTypedata();
    $newargs = [];
    foreach ($post_types as $typename) {
        if (!isset($datas[$typename]) || !$datas[$typename]['queue']) {
            continue;
        }
        $newargs[$typename] = $datas[$typename];
        if (in_array('category', $datas[$typename]['tasks']) && !empty($datas[$typename]['categories'])) {
            // 获取分类列表通过get_terms
            $categories = get_terms([
                'taxonomy' => $datas[$typename]['categories'],
                'hide_empty' => false,
                'orderby' => 'name',
                'order' => 'ASC'
            ]);
            if (is_wp_error($categories)) {
                $categories = [];
            }
            $categories_list = [];
            foreach ($categories as $category) {
                $categories_list[] = [
                    'id' => $category->term_id,
                    'name' => $category->name,
                ];
            }
            $newargs[$typename]['categoriesList'] = $categories_list;
        }
    }
    return $newargs;
}

function xh_postType_config($type, $subtype = '')
{
    $datas = xh_postTypedata($type);
    if (!is_array($datas)) {
        return [];
    }

    $rules_json = get_option('xhtheme_ai_toolbox_automate_rules', '[]');
    $rules_data = json_decode($rules_json, true);

    if (empty($rules_data)) {
        $rules_data = xh_migrate_automate_config();
    }

    $datas['queue'] = false;
    $newtasks = [];
    if (is_array($rules_data) && !empty($rules_data)) {
        foreach ($rules_data as $rule) {
            if ($rule['enabled'] && $rule['postType'] === $type) {
                if ($rule['defaultTrigger'] == 'auto') {
                    $datas['queue'] = true;
                }

                // publishOnStatuses
                $datas['autopublish'] = [];
                if (isset($rule['publishOnStatuses']) && is_array($rule['publishOnStatuses'])) {
                    $datas['autopublish'] = $rule['publishOnStatuses'];
                }

                if (isset($rule['tasks']) && is_array($rule['tasks'])) {
                    foreach ($rule['tasks'] as $task_key => $task_config) {
                        if (is_array($task_config)) {
                            if ($task_config['enabled'] && xh_automation_task_enabled($task_key)) {
                                $newtasks[$task_key] = $task_config['categories'];
                            }
                        }
                    }
                }
            }
        }
    }

    $datas['tasks'] = $newtasks;
    if (empty($newtasks)) {
        $datas['queue'] = false;
    }
    if ($subtype) {
        return isset($datas[$subtype]) ? $datas[$subtype] : false;
    }
    return $datas;
}

function xh_autooption($post_type, $name, $subtype = '')
{
    static $xhautooptions_cache = [];

    if (!isset($xhautooptions_cache[$post_type])) {
        $config = xh_postType_config($post_type);
        $xhautooptions_cache[$post_type] = $config ? $config : [];
    }

    $xhautooptions_data = $xhautooptions_cache[$post_type];

    if (isset($xhautooptions_data[$name])) {
        if ($subtype) {
            return isset($xhautooptions_data[$name][$subtype]) ? $xhautooptions_data[$name][$subtype] : false;
        }
        return $xhautooptions_data[$name];
    }
    return false;
}

/**
 * 挂载错误处理
 */
function xhaitoolbox_log_error($errorMsg, $data = [])
{
    do_action('xhaitoolbox_log_error', $errorMsg, $data);
}


/**
 * 记录错误日志
 */
function insert_debuglog($name, $error)
{
    $error_log = get_transient('xhtheme_ai_toolbox_error_log');
    if (!$error_log || !is_array($error_log)) {
        $error_log = [];
    }
    $error_log[] = [
        'name' => $name,
        'time' => wp_date('Y-m-d H:i:s'),
        'log' => $error
    ];
    set_transient('xhtheme_ai_toolbox_error_log', $error_log, 600);
}

/**
 * 生成随机时间
 */
function xh_randTimeList($startTimeStr, $endDay, $numNodes)
{
    $startTimestamp = $startTimeStr ? strtotime($startTimeStr) : xh_local_timestamp();
    $endTimestamp = $startTimestamp + $endDay * 86400;
    $duration = $endTimestamp - $startTimestamp;

    if ($duration <= 0 || $numNodes <= 0) {
        return [];
    }

    $nodes = [];
    $generated = 0;
    $attempts = 0;

    $getRandomFloat = function () {
        if (class_exists('\Random\Randomizer')) {
            static $randomizer = null;
            if (!$randomizer) {
                $randomizer = new \Random\Randomizer();
            }
            if (method_exists($randomizer, 'getFloat')) {
                return $randomizer->getFloat(0, 1); // [0, 1)
            }
        }
        return lcg_value();
    };

    while ($generated < $numNodes && $attempts < $numNodes * 20) {
        $attempts++;

        $rand = pow($getRandomFloat(), 2);
        $timeOffset = (int) ($rand * $duration);
        $nodeTimestamp = $startTimestamp + $timeOffset;

        // 跳过凌晨1点到7点 - 需要使用本地时区判断
        // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date -- Local timezone needed for user behavior simulation
        $hour = (int) wp_date('G', $nodeTimestamp);
        if ($hour >= 1 && $hour < 7) {
            continue;
        }

        // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date -- Local timezone needed for consistency with WordPress
        $nodes[] = wp_date('Y-m-d H:i:s', $nodeTimestamp);
        $generated++;
    }

    sort($nodes);
    return $nodes;
}

/**
 * 获取文章语言
 */
function xh_post_language($post_id = null)
{
    $localeOption = xh_option('languageType', 'auto');
    if ($localeOption == 'webauto') {
        return 'auto';
    }
    if ($localeOption == 'auto') {
        if (!$post_id) {
            global $post;
            if (!$post || !isset($post->ID)) {
                return 'auto';
            }
            $post_id = $post->ID;
        }

        if (function_exists('pll_get_post_language')) {
            $language_code = pll_get_post_language($post_id, 'locale');
            if (!empty($language_code)) {
                return $language_code;
            }
        }

        if (defined('ICL_SITEPRESS_VERSION') || function_exists('wpml_get_language_information')) {
            $post_type = get_post_type($post_id);
            $args = array('element_id' => $post_id, 'element_type' => 'post_' . $post_type);
            // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Using WPML plugin hook
            $language_details = apply_filters('wpml_element_language_details', null, $args);

            if (is_object($language_details) && !empty($language_details->language_code)) {
                if ($language_details->language_code == 'zh-hant' || $language_details->language_code == 'zh-tw') {
                    return 'zh_TW';
                }
                if ($language_details->language_code == 'zh-hans' || $language_details->language_code == 'zh-cn') {
                    return 'zh_CN';
                }
                if ($language_details->language_code == 'en') {
                    return 'en_US';
                }
                return $language_details->language_code;
            }
        }
        return get_locale();
    }
    return $localeOption;
}

/**
 * 判断分类是否符合要求
 */
function xh_filter_category($post, $config, $taxonomy, $default_category = 0, $autoCategory = false)
{
    if (!$config || !is_array($config) || !isset($config['type']) || !$taxonomy) {
        return 1;
    }

    $filterType = $config['type'];
    if ($filterType == 'all') {
        return 1;
    }

    // 获取文章的分类ID列表
    $post_categories = is_array($taxonomy) && !empty($taxonomy) ? $taxonomy : wp_get_object_terms($post->ID, $taxonomy, ['fields' => 'ids']);

    if (empty($post_categories) || is_wp_error($post_categories)) {
        return $autoCategory ? 2 : 1;
    }

    if ($autoCategory && $default_category && count($post_categories) == 1 && in_array($default_category, $post_categories)) {
        return 2;
    }

    $list = isset($config['list']) ? $config['list'] : [];
    switch ($filterType) {
        case 'whitelist':
            if (empty($list)) {
                return 0;
            }
            $has_matching_category = !empty(array_intersect($post_categories, $list));
            return $has_matching_category ? 1 : 0;

        case 'blacklist':
            if (empty($list)) {
                return 1;
            }
            $has_excluded_category = !empty(array_intersect($post_categories, $list));
            return $has_excluded_category ? 0 : 1;
    }
    return 0;
}

function xh_loop_filter_category($postId, $config, $newCategory = [])
{
    $post = get_post($postId);
    if (!$post) {
        return false;
    }
    $taxonomy = xh_postType_config($post->post_type, 'categories');
    $default_category = $taxonomy ? get_option('default_' . $taxonomy) : 0;
    return xh_filter_category($post, $config, !empty($newCategory) ? $newCategory : $taxonomy, $default_category, false);
}

function xh_check_hold_task($task, $postId)
{
    // 根据文章ID获取文章的所有任务
    $XHCron = XHCronQueue::getInstance();
    $CronItems = $XHCron->postTasks($postId);
    if (!$CronItems || !is_array($CronItems))
        return;
    $loadList = [];
    $priorityList = [];
    foreach ($CronItems as $CronItem) {
        if ($CronItem['type'] == $task || $CronItem['status'] !== 'freeze') {
            continue;
        }
        $setdata = [
            'status' => 'hold'
        ];
        $cron_id = $CronItem['cron_id'];
        $itemData = isset($CronItem['data']) && !empty($CronItem['data']) ? json_decode($CronItem['data'], true) : [];
        if ($CronItem['type'] == 'primary') {
            if (isset($itemData['postterms'])) {
                $itemData['config']['taskStatus'] = 1;
                $setdata['data'] = $itemData;
                $priorityList[$cron_id] = $setdata;
            } else {
                $loadList[$cron_id] = $setdata;
            }
        } else {
            if (isset($itemData['config']['categories'])) {
                $loadList[$cron_id] = $setdata;
            } else {
                $priorityList[$cron_id] = $setdata;
            }
        }
    }
    if ($priorityList && isset($priorityList['primary_' . $postId])) {
        foreach ($priorityList as $taskId => $item) {
            $XHCron->update($taskId, $item);
        }
        return;
    }

    $newList = $loadList + $priorityList;
    if ($newList && is_array($newList)) {
        foreach ($newList as $taskId => $item) {
            $XHCron->update($taskId, $item);
        }
    }
    return;
}

/**
 * 检查文章是否符合自动发布状态
 */
function xh_check_publish_status($post, $cron_id)
{
    if (!is_a($post, 'WP_Post')) {
        $post = get_post($post);
        if (!$post)
            return;
    }
    $checkStatus = xh_postType_config($post->post_type, 'autopublish');
    if (!$checkStatus || !is_array($checkStatus) || !in_array($post->post_status, $checkStatus))
        return false;
    $XHCron = XHCronQueue::getInstance();
    $CronItems = $XHCron->postTasks($post->ID);
    if (!$CronItems) {
        return true;
    }
    foreach ($CronItems as $Cron) {
        if ($Cron['cron_id'] == $cron_id || $Cron['status'] == 'skip') {
            continue;
        }
        return false;
    }
    return true;
}

function xh_loop_auto_publish($post, $cron_id)
{
    if (!is_a($post, 'WP_Post')) {
        $post = get_post($post);
        if (!$post)
            return;
    }
    if ($post->post_status !== 'publish' && xh_check_publish_status($post, $cron_id)) {
        $updatePost = [
            'ID' => $post->ID,
            'post_status' => 'publish'
        ];
        wp_update_post($updatePost);
    }
}

/**
 * 自动化配置迁移适配函数
 */
function xh_migrate_automate_config()
{
    if (get_transient('xhtheme_ai_toolbox_automate_migrated')) {
        return [];
    }

    $oldConfig = get_option('xhtheme_ai_toolbox_automate', '');
    if (empty($oldConfig)) {
        return [];
    }

    // 检查是否已有新配置
    $new_rules = get_option('xhtheme_ai_toolbox_automate_rules', '[]');
    $new_rules_data = json_decode($new_rules, true);
    if (is_array($new_rules_data) && !empty($new_rules_data)) {
        return $new_rules_data;
    }


    // 开始适配
    $old_configArr = json_decode($oldConfig, true);
    if (!is_array($old_configArr) || empty($old_configArr)) {
        return [];
    }

    // 获取所有公开的文章类型
    $post_types = get_post_types(array(
        'public' => true,
        '_builtin' => false
    ), 'names');
    if (!$post_types) {
        $post_types = [];
    }
    $post_types = array_keys($post_types);
    $post_types = array_merge(['post'], $post_types);

    // 获取支持的文章类型数据
    $datas = xh_postTypedata();

    // 开始迁移
    $migrated_rules = [];
    $timestamp = wp_date('Y-m-d H:i:s');

    // 遍历每个文章类型创建规则
    foreach ($post_types as $post_type) {
        if (!isset($datas[$post_type])) {
            continue;
        }

        $type_data = $datas[$post_type];
        $rule_tasks = [];
        $has_enabled_task = false;
        if (!isset($type_data['tasks']) || empty($type_data['tasks'])) {
            continue;
        }

        foreach ($type_data['tasks'] as $taskName) {
            $oldTaskobj = isset($old_configArr[$taskName]) ? $old_configArr[$taskName] : [];
            if (!isset($oldTaskobj['enabled'])) {
                continue;
            }
            $task_enabled = (bool) $oldTaskobj['enabled'];
            if (isset($oldTaskobj['notypes']) && is_array($oldTaskobj['notypes']) && in_array($post_type, $oldTaskobj['notypes'])) {
                $task_enabled = false;
            }

            $rule_tasks[$taskName] = [
                'enabled' => $task_enabled,
                'categories' => [
                    'type' => 'all',
                    'list' => []
                ]
            ];

            if ($task_enabled) {
                $has_enabled_task = true;
            }
        }

        if ($has_enabled_task) {
            $defaultTrigger = isset($old_configArr['aistatus']['enabled']) && $old_configArr['aistatus']['enabled'] && !in_array($post_type, $old_configArr['aistatus']['notypes']) ? 'auto' : 'manual';
            $migrated_rules[] = [
                'id' => $post_type . '_' . time(),
                'name' => $type_data['name'],
                'postType' => $post_type,
                'enabled' => true,
                'defaultTrigger' => $defaultTrigger,
                'publishOnStatuses' => ['pending'],
                'tasks' => $rule_tasks,
                'createdAt' => $timestamp,
                'updatedAt' => $timestamp
            ];
        }
    }

    if (!empty($migrated_rules)) {
        update_option('xhtheme_ai_toolbox_automate_rules', wp_json_encode($migrated_rules));
        set_transient('xhtheme_ai_toolbox_automate_migrated', 'load', 86400 * 7);
        return $migrated_rules;
    }

    return [];
}

/**
 * 获取主题名称
 */
function xh_themeName()
{
    if (defined('B2_VERSION')) {
        return '7B2';
    } elseif (defined('ZIB_ROOT_PATH')) {
        return 'Zibll';
    }
    $theme = wp_get_theme();
    $themeName = $theme->get('Name');
    if ($themeName == '子比主题') {
        return 'Zibll';
    } elseif ($themeName == 'B2 PRO') {
        return '7B2';
    }
    return $themeName;
}

/**
 * 主题适配提醒
 */
function xh_themefitter_notice()
{
    $hidden_notices = get_option('xhaitool_theme_notices', []);
    $fitters = [];
    if (defined('zck_plugin_path')) {
        if (!in_array('zck-v1', $hidden_notices)) {
            $fitters['zck-v1'] = [
                'title' => '<strong>智创客插件</strong> 如果遇到采集时无法触发自动任务，请按教程进行适配！',
                'url' => 'https://www.xhtheme.com/docs/aitoolbox/adaptation-custom/zybk-plugin',
            ];
        }
    }
    return $fitters;
}

/**
 * 过滤内容
 */
function xh_stripfilter_tags($content)
{
    if ($content === '') {
        return '';
    }

    return preg_replace(
        [
            '/<script\b[^>]*>.*?<\/script>/is',
            '/<iframe\b[^>]*>.*?<\/iframe>/is',
        ],
        '',
        $content
    );
}


function xh_filterContent($content, $post = null)
{
    $content = xh_stripfilter_tags($content);
    $postContent = '';
    if ($post instanceof \WP_Post) {
        remove_filter('the_content', [XHThemeAi::getInstance(), 'ai_postexcerpt'], 99);
        remove_filter('the_content', [XHThread::getInstance(), 'threads_after_content']);
        $postContent = apply_filters(
            'the_content',
            get_the_content(null, false, $post)
        );
        $postContent = str_replace(']]>', ']]&gt;', $postContent);
        $postContent = xh_stripfilter_tags($postContent);
    }
    $contentLength     = mb_strlen(wp_strip_all_tags($content), 'UTF-8');
    $postContentLength = mb_strlen(wp_strip_all_tags($postContent), 'UTF-8');

    return $contentLength >= $postContentLength ? $content : $postContent;
}

/**
 * 图片转换为 Base64
 */
function xh_image_to_base64($image_url, $max_side = 768, $quality = 90)
{
    $max_file_size = 10 * 1024 * 1024;
    $upload_dir = wp_upload_dir();
    $image_path = '';
    $file_content = '';

    // 优先尝试本地文件
    if (strpos($image_url, $upload_dir['baseurl']) !== false) {
        $image_path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $image_url);
    }

    if (!empty($image_path) && file_exists($image_path)) {
        if (filesize($image_path) > $max_file_size) {
            return new \WP_Error('file_too_large', __('Image file exceeds maximum size limit', 'xhtheme-ai-toolbox'));
        }
        $file_content = file_get_contents($image_path);
    } else {
        $response = wp_remote_get($image_url, array(
            'timeout' => 15,
            'headers' => array(
                'Referer'    => home_url('/'),
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            ),
            'sslverify' => false
        ));

        if (is_wp_error($response)) {
            return $response;
        }

    $status_code = wp_remote_retrieve_response_code($response);
    if ($status_code !== 200) {
        /* translators: %d: HTTP status code returned when fetching the image. */
        return new \WP_Error('http_error', sprintf(__('Failed to fetch image, HTTP status: %d', 'xhtheme-ai-toolbox'), $status_code));
    }

        $file_content = wp_remote_retrieve_body($response);

        if (strlen($file_content) > $max_file_size) {
            return new \WP_Error('file_too_large', __('Image file exceeds maximum size limit', 'xhtheme-ai-toolbox'));
        }
    }

    if (empty($file_content)) {
        return new \WP_Error('empty_content', __('Image content is empty', 'xhtheme-ai-toolbox'));
    }

    if (!function_exists('wp_tempnam')) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
    }
    $tmp_file = wp_tempnam();
    if (empty($tmp_file) || !is_string($tmp_file)) {
        return new \WP_Error('temp_file_error', __('Failed to create temporary file', 'xhtheme-ai-toolbox'));
    }

    $write_result = file_put_contents($tmp_file, $file_content);
    if ($write_result === false) {
        if (file_exists($tmp_file)) {
            wp_delete_file($tmp_file);
        }
        return new \WP_Error('temp_file_write_error', __('Failed to write temporary file', 'xhtheme-ai-toolbox'));
    }

    $editor = wp_get_image_editor($tmp_file);
    $mime_type = 'image/jpeg';

    if (!is_wp_error($editor)) {
        $size = $editor->get_size();
        $editor->set_quality($quality);

        if ($size['width'] > $max_side || $size['height'] > $max_side) {
            $editor->resize($max_side, $max_side, false);
        }

        $saved = $editor->save($tmp_file, 'image/jpeg');

        if (!is_wp_error($saved) && file_exists($saved['path'])) {
            $processed_content = file_get_contents($saved['path']);
            if ($saved['path'] !== $tmp_file) {
                wp_delete_file($saved['path']);
            }
        } else {
            $processed_content = file_get_contents($tmp_file);
        }
    } else {
        $processed_content = $file_content;
    }

    wp_delete_file($tmp_file);

    return 'data:' . $mime_type . ';base64,' . base64_encode($processed_content);
}

/**
 * 上传图片到临时中转服务器（带缓存）
 * 
 * @param string $image_url 图片 URL
 */
function xh_upload_tmp_image($image_url)
{
    $cache_key = 'xh_tmpimg_' . md5($image_url);
    $cached = get_transient($cache_key);
    if ($cached !== false && is_array($cached)) {
        return $cached;
    }

    $base64_image = xh_image_to_base64($image_url);

    if (is_wp_error($base64_image)) {
        return $base64_image;
    }

    $appid = xh_option('appId', '');
    $response = wp_remote_post(XHTHEME_AI_TOOLBOX_IMAGE_TMPURL, array(
        'headers' => array(
            'Content-Type'  => 'application/json',
            'Authorization' => 'Bearer ' . $appid
        ),
        'body'    => wp_json_encode(array('image' => $base64_image)),
        'timeout' => 10
    ));

    if (is_wp_error($response)) {
        return $response;
    }

    $status_code = wp_remote_retrieve_response_code($response);
    if ($status_code !== 200) {
        /* translators: %d: HTTP status code returned by the remote upload service. */
        return new \WP_Error('http_error', sprintf(__('Upload failed, HTTP status: %d', 'xhtheme-ai-toolbox'), $status_code));
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);
    if (!isset($body['code']) || $body['code'] !== 0) {
        $message = isset($body['message']) ? $body['message'] : __('Upload failed', 'xhtheme-ai-toolbox');
        return new \WP_Error('upload_failed', $message);
    }
    $expires_ttl = isset($body['data']['expires']) ? intval($body['data']['expires']) : 86400;
    $filename = isset($body['data']['filename']) ? sanitize_file_name($body['data']['filename']) : '';

    $result = array(
        'type'    => 'filename',
        'data'    => $filename,
        'expires' => $expires_ttl,
    );
    $cache_duration = max(0, $expires_ttl - 600);
    if ($cache_duration > 0) {
        set_transient($cache_key, $result, $cache_duration);
    }

    return $result;
}

/**
 * 调用临时图片
 */
function xh_get_imagevl($content)
{
    if (empty($content)) {
        return null;
    }
    $text_length = mb_strlen(wp_strip_all_tags($content), 'UTF-8');
    if ($text_length > 500) {
        return null;
    }
    if (!preg_match('/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i', $content, $matches)) {
        return null;
    }

    $image_url = $matches[1];
    if (empty($image_url)) {
        return null;
    }
    $result = xh_upload_tmp_image($image_url);
    if (is_wp_error($result)) {
        return null;
    }

    return $result;
}


/**
 * 任务优化
 */
function xh_clear_overduecrons()
{
    set_transient('xhaitoolbox_clear_overduecrons_2', time(), 86400);

    global $wpdb;
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Checking cron option existence
    $exists = $wpdb->get_var($wpdb->prepare(
        "SELECT option_id FROM $wpdb->options WHERE option_id = %d AND option_name = %s",
        1,
        'cron'
    ));
    if ($exists) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Deleting corrupted cron option
        $wpdb->delete(
            $wpdb->options,
            array('option_id' => 1, 'option_name' => 'cron'), // 删除条件
            array('%d', '%s')
        );
        _set_cron_array(array());
        return;
    }

    $crons = _get_cron_array();
    if (empty($crons) || !is_array($crons)) {
        return;
    }
    if (count($crons) > 2000) {
        _set_cron_array(array());
        return;
    }
    $has_changes = false;
    $deleted_count = 0;
    $repeatArr = [];
    foreach ($crons as $timestamp => $hooks) {
        $uidkey = md5(serialize($hooks));
        if (in_array($uidkey, $repeatArr)) {
            unset($crons[$timestamp]);
            $has_changes = true;
            $deleted_count++;
            continue;
        }
        $repeatArr[] = $uidkey;
    }
    if ($has_changes) {
        _set_cron_array($crons);
        xhaitoolbox_log_error(esc_html("已清理 {$deleted_count} 个重复的时间戳任务组。"));
    }
}

/**
 * 获取 AI API URL
 */
function xh_apiurl()
{
    $defaultUrl = defined('XHTHEME_AI_TOOLBOX_API_URL')
        ? XHTHEME_AI_TOOLBOX_API_URL
        : 'https://ai.xhtheme.com/airest/chat';

    return apply_filters('xhaitoolbox_ai_api_url', $defaultUrl);
}

/**
 * 获取 AI 版本号
 */
function xh_aiversion()
{
    return get_option('xhtheme_aitoolbox_chatversion', '1.0');
}

/**
 * 判断是否为会员用户
 * @return bool
 */
function xh_ismember()
{
    static $result = null;
    if ($result === null) {
        $ai = XHThemeAi::getInstance();
        $result = $ai->isMember();
    }
    return $result;
}

/**
 * 模型错误通知
 */
function xh_modelerror($errorType, $errorMsg = '')
{
    $admin_email = get_option('admin_email');
    switch ($errorType) {
        case 'appId':
            wp_mail(
                $admin_email,
                __('[XHTheme AI Toolbox] APPID information not configured, scheduled task has been suspended', 'xhtheme-ai-toolbox'),
                __('Due to the failure to obtain APPID information, the AI interface is unavailable. The current scheduled task has been temporarily stopped and will be retried after 2 hours!', 'xhtheme-ai-toolbox')
            );
            break;
        default:
            break;
    }
}

/**
 * 统一 AI API 请求函数
 */
function xh_api_request($type, $body = [], $post = null, $outputType = 'aidata',$timeout = 0)
{
    $appid = xh_option('appId', '');
    if (empty($appid)) {
        xh_modelerror('appId', '');
        return new \WP_Error('config_error', 'AppID not configured');
    }
    $defaults = [
        'type' => $type,
        'apivar' => XHTHEME_AI_TOOLBOX_APIVERSION,
        'stream' => false,
        'backstage' => true,
        'imagerec' => xh_option('imageRecognition', true),
        'model' => xh_option('modelType', 'auto'),
        'version' => xh_aiversion(),
        'timestamp' => time(),
    ];
    if ($post) {
        if (is_numeric($post)) {
            $post = get_post($post);
        }
        if ($post instanceof \WP_Post) {
            $postContent = xh_filterContent($post->post_content, $post);
            $postTypedata = xh_postTypedata($post->post_type);
            $defaults['content'] = $postContent;
            $defaults['imagevl'] = xh_get_imagevl($postContent);
            $defaults['posttitle'] = $post->post_title;
            $defaults['posttype'] = isset($postTypedata['slug']) ? $postTypedata['slug'] : $post->post_type;
            $defaults['language'] = xh_post_language($post->ID);
        }
    }
    $merged_body = wp_parse_args($body, $defaults);
    $response = wp_remote_post(xh_apiurl(), [
        'headers' => [
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $appid,
            'Referer' => home_url()
        ],
        'body' => wp_json_encode($merged_body),
        'timeout' => $timeout > 5 ? $timeout : XHTHEME_AI_TOOLBOX_APITIMEOUT,
        'sslverify' => false
    ]);
    if (is_wp_error($response)) {
        return new \WP_Error('request_error', $response->get_error_message());
    }

    $response_body = wp_remote_retrieve_body($response);
    $data = json_decode($response_body, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        return new \WP_Error('data_error', 'Invalid JSON response',[
            'content' => $response_body
        ]);
    }

    if (isset($data['code']) && $data['code'] !== 0) {
        return new \WP_Error('api_error', $data['message'] ?? 'Unknown API error', [
            'content' => $response_body,
            'code' => $data['code']
        ]);
    }
    if ($outputType === 'aidata') {
        return $data['data']['aidata'] ?? [];
    }
    return $data['data'] ?? [];
}

/**
 * 统一处理 xh_api_request 返回的错误
 */
function xh_api_handle_error($error, $cronArr, $logPrefix = '[XHAi]')
{
    if (!is_wp_error($error)) {
        return $cronArr;
    }

    $errorCode = $error->get_error_code();
    $errorMessage = $error->get_error_message();
    $errorData = $error->get_error_data();
    $apiCode = isset($errorData['code']) ? $errorData['code'] : 0;
    if($errorCode && !isset($errorData['errorcode']) ){
        $errorData['errorcode'] = $errorCode;
    }

    $cronArr['message'] = $errorMessage;
    if ($errorCode === 'config_error') {
        return $cronArr;
    }
    if (in_array($errorCode, ['request_error', 'data_error'], true)) {
        xhaitoolbox_log_error($logPrefix . ' ' . $errorCode . ' (will retry): ' . $errorMessage, $errorData);
        return $cronArr;
    }
    $errorNum = (int) ($cronArr['errornum'] ?? 0) + 1;
    $cronArr['errornum'] = $errorNum;
    if ($apiCode == 2 || $errorNum >= 5) {
        $cronArr['status'] = 'error';
        xhaitoolbox_log_error($logPrefix . ' API error (marked failed): ' . $errorMessage, $errorData);
    } else {
        xhaitoolbox_log_error($logPrefix . ' API error (attempt ' . $errorNum . '): ' . $errorMessage, $errorData);
    }

    return $cronArr;
}

/**
 * 插入队列任务
 */
function xh_cron_insert($id, $type, $data = [], $priority = 0, $status = 'hold', $scheduled = null)
{
    return XHCronQueue::getInstance()->insert($id, $type, $data, $priority, $status, $scheduled);
}

/**
 * 获取队列任务
 */
function xh_cron_getrow($cronId, $status = '')
{
    return XHCronQueue::getInstance()->getrow($cronId, $status);
}

/**
 * 解析 AI 头像数据
 */
function xh_parse_avatar($avatar_data)
{
    if (empty($avatar_data)) {
        return '';
    }

    // 直接是 URL
    if (filter_var($avatar_data, FILTER_VALIDATE_URL)) {
        return $avatar_data;
    }

    // 尝试解析 JSON
    if (!is_array($avatar_data)) {
        $data = json_decode($avatar_data, true);
        if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
            return '';
        }
    } else {
        $data = $avatar_data;
    }

    if (isset($data['url']) && filter_var($data['url'], FILTER_VALIDATE_URL)) {
        return $data['url'];
    }
    if (isset($data['type']) && $data['type'] === 'local' && !empty($data['hash'])) {
        if (!class_exists(__NAMESPACE__ . '\\XH_AvatarLocal')) {
            require_once plugin_dir_path(__FILE__) . '../classes/class-xhtheme-avatarlocal.php';
        }

        $local_avatar = XH_AvatarLocal::download_avatar($data['hash']);
        if ($local_avatar) {
            return $local_avatar;
        }
    }

    return '';
}

/**
 * 获取 AI 评论助手配置
 */
function xh_get_interact($key = null, $default = null)
{
    return XHInteract::getInstance()->get_settings($key, $default);
}

/**
 * 清理召唤词缓存
 */
function xh_clear_aiwords_cache()
{
    delete_transient('xhinteract_aiwords');
}

/**
 * 获取召唤词映射
 */
function xh_get_aiwords()
{
    $cache = get_transient('xhinteract_aiwords');
    if ($cache === false) {
        $summon_map = [];
        $moderator = xh_get_interact('moderator');
        if (!empty($moderator['enabled'])) {
            $bindings = $moderator['bindings'] ?? [];
            foreach ($bindings as $binding) {
                $user_id = absint($binding['user_id'] ?? 0);
                if (!$user_id) {
                    continue;
                }

                $keywords = $binding['keywords'] ?? [];
                foreach ($keywords as $keyword) {
                    $keyword = trim($keyword);
                    if (!empty($keyword)) {
                        $summon_map[$keyword] = $user_id;
                    }
                }
            }
        }
        $cache = $summon_map;
        set_transient('xhinteract_aiwords', $summon_map, WEEK_IN_SECONDS);
    }

    return is_array($cache) ? $cache : [];
}
