<?php

namespace XHTheme\AIToolbox;

defined('ABSPATH') || exit;

final class XHAiimage
{

    private static $instance;

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

    private function __construct() {}


    private function init()
    {
        add_action('rest_after_insert_post', [$this, 'generate_aiimages'], 10, 1);
        add_filter('xhaitoolbox_cronitem_imageword', [$this, 'process_imageword'], 10, 3);
        add_filter('xhaitoolbox_cronitem_getimage', [$this, 'process_getimage'], 10, 3);
    }

    /**
     * 获取模型代码（优先使用新字段，兼容旧字段）
     */
    private function get_model_code($platform)
    {
        $modelCode = xh_option('imageModelCode', '');
        if (!empty($modelCode)) {
            return $modelCode;
        }

        // 旧数据迁移映射
        $oldModel = xh_option('imageModel', 'flash');
        $migrationMap = [
            'aliyun' => ['flash' => 'qwen-image-plus', 'plus' => 'qwen-image'],
            'cogview' => ['flash' => 'cogview-3-flash', 'plus' => 'cogview-4-250304']
        ];

        return isset($migrationMap[$platform][$oldModel]) ? $migrationMap[$platform][$oldModel] : '';
    }

    /**
     * 获取阿里云百炼接口地址（按节点）
     */
    private function get_aliyun_generation_endpoint()
    {
        $region = strtolower(trim((string) xh_option('imageAliyunRegion', 'beijing')));
        $regionHosts = [
            'beijing' => 'dashscope.aliyuncs.com',
            'singapore' => 'dashscope-intl.aliyuncs.com'
        ];
        $host = isset($regionHosts[$region]) ? $regionHosts[$region] : $regionHosts['beijing'];

        return 'https://' . $host . '/api/v1/services/aigc/multimodal-generation/generation';
    }


    /**
     * 获取图片尺寸配置
     */
    private function get_imagesize($model = '', $separator = 'x')
    {
        $imageSize = xh_option('imageSize', '1280x768');
        $parts = explode('x', strtolower($imageSize));
        $width  = isset($parts[0]) ? (int) $parts[0] : 1280;
        $height = isset($parts[1]) ? (int) $parts[1] : 768;

        $imageType = 'square';
        if ($width > $height) {
            $imageType = 'landscape';
        } elseif ($width < $height) {
            $imageType = 'portrait';
        }

        $sizeRules = [
            'default' => [
                'landscape' => [1280, 720],
                'portrait'  => [720, 1280],
                'square'    => [1280, 1280]
            ],
            'qwenimage' => [
                'landscape' => [1664, 928],
                'portrait'  => [928, 1664],
                'square'    => [1328, 1328]
            ],
            'cogview' => [
                'landscape' => [1728, 960],
                'portrait'  => [960, 1728],
                'square'    => [1280, 1280]
            ]
        ];

        $pattern = 'default';
        if (strpos($model, 'qwen-image') === 0) {
            $pattern = 'qwenimage';
        } elseif (strpos($model, 'cogview') === 0 || strpos($model, 'glm-image') === 0) {
            $pattern = 'cogview';
        }
        $patternSize = apply_filters('xhaitoolbox_image_size_rules', [], $model, $pattern, $imageType);
        if (empty($patternSize) || !isset($patternSize[$imageType])) {
            $patternSize = isset($sizeRules[$pattern]) ? $sizeRules[$pattern] : $sizeRules['default'];
        }
        return join($separator, $patternSize[$imageType]);
    }

    /**
     * 安全解析 API JSON 响应
     */
    private function decode_api_json_body($body)
    {
        if (!is_string($body) || $body === '') {
            return [];
        }

        $decoded = json_decode($body, true);
        return is_array($decoded) ? $decoded : [];
    }

    /**
     * 提取统一 aidata 数据结构
     */
    private function extract_api_aidata($resData)
    {
        if (!is_array($resData) || !isset($resData['data']) || !is_array($resData['data'])) {
            return [];
        }
        if (!isset($resData['data']['aidata']) || !is_array($resData['data']['aidata'])) {
            return [];
        }

        return $resData['data']['aidata'];
    }

    /**
     * 生成图片提示词任务
     */
    public function process_imageword($CronItem, $cronType, $postId)
    {
        if (empty($postId)) {
            $CronItem['status'] = 'error';
            $CronItem['message'] = esc_html__('Invalid parameters [code:003]', 'xhtheme-ai-toolbox');
            return $CronItem;
        }

        $config = isset($CronItem['data']['config']) && is_array($CronItem['data']['config']) ? $CronItem['data']['config'] : [];

        /**
         * 分类过滤
         */
        if ($config && !isset($config['taskStatus']) && isset($config['categories'])) {
            $filter_category = xh_loop_filter_category($postId, $config['categories']);
            if (!$filter_category) {
                $CronItem['status'] = 'skip';
                $CronItem['message'] = esc_html__('Category not match', 'xhtheme-ai-toolbox');
                // 跳过判断文章是否需要发布
                xh_loop_auto_publish($postId, $CronItem['cron_id'] ?? 0);
                return $CronItem;
            }
        }

        $post = get_post($postId);
        if (!$post) {
            $CronItem['status'] = 'error';
            return $CronItem;
        }
        $aiimageword = get_post_meta($postId, '_aiimage_cueword', true);
        if (!$aiimageword) {
            $apiArgs = isset($CronItem['data']) && is_array($CronItem['data']) ? $CronItem['data'] : [];
            $apiArgs['imagePromptLevel'] = sanitize_key((string) ($apiArgs['imagePromptLevel'] ?? xh_option('imagePromptLevel', 'safe')));
            if (!in_array($apiArgs['imagePromptLevel'], ['safe', 'aggressive'], true)) {
                $apiArgs['imagePromptLevel'] = 'safe';
            }
            // 使用统一 API 请求函数
            $result = xh_api_request('post-aiimage', ['args' => $apiArgs], $post);
            if (is_wp_error($result)) {
                return xh_api_handle_error($result, $CronItem, '[XHAiimage]');
            }

            if (isset($result['content'])) {
                $content = $result['content'];
                if ($content) {
                    $aiimageword = $content;
                    update_post_meta($postId, '_aiimage_cueword', $aiimageword);
                }
            }
        }

        if (!$aiimageword) {
            // 没有获取到提示词，增加错误计数等待重试
            $errorNum = (int) ($CronItem['errornum'] ?? 0) + 1;
            $CronItem['errornum'] = $errorNum;
            $CronItem['message'] = esc_html__('Failed to generate image prompt!', 'xhtheme-ai-toolbox');
            if ($errorNum >= 5) {
                $CronItem['status'] = 'error';
            }
            return $CronItem;
        }

        /**
         * 提交生图任务
         */
        $imagePattern = xh_option('imagePlatform', 'default');
        if (!in_array($imagePattern, ['default', 'aliyun', 'cogview'])) {
            $imagePattern = 'default';
        }
        $apires = $this->imageapi_create($aiimageword, $imagePattern);
        if ($apires['success']) {
            update_post_meta($postId, '_aiimage_status', -1);
            $CronItem['status'] = 'success';
            // 不触发队列
            if (isset($apires['notask']) && $apires['notask']) {
                $postRes = $this->process_post($CronItem, $postId, $apires['imageUrl'], 'imageword');
                if (is_wp_error($postRes)) {
                    $CronItem['status'] = 'error';
                    $CronItem['message'] = '[' . $postRes->get_error_code() . '] ' . $postRes->get_error_message();
                    $errorData = $postRes->get_error_data();
                    $logMessage = '[XHAiimage] postId:' . $postId . ' [' . $postRes->get_error_code() . '] ' . $postRes->get_error_message();
                    if (is_array($errorData)) {
                        foreach ($errorData as $key => $value) {
                            $logMessage .= ' - ' . $key . ': ' . $value;
                        }
                    }
                    xhaitoolbox_log_error($logMessage);
                    return $CronItem;
                }
                // 落库成功后才删除提示词
                delete_post_meta($postId, '_aiimage_cueword');
            } else {
                $Cronrow = xh_cron_getrow('getimage' . '_' . $postId);
                if (!$Cronrow) {
                    $taskData = [
                        'task_id' => $apires['task_id'],
                        'pattern' => $imagePattern
                    ];
                    if ($config && isset($config['taskStatus'])) {
                        $taskData['config']['taskStatus'] = 1;
                    }
                    xh_cron_insert($postId, 'getimage', $taskData, 3);
                }
                // 异步任务已入队，提示词不再需要
                delete_post_meta($postId, '_aiimage_cueword');
            }
        } else {
            $errorNum = (int) ($CronItem['errornum'] ?? 0);
            $errorNum = $errorNum + 1;
            $CronItem['errornum'] = $errorNum;
            if (isset($apires['type']) && $apires['type'] == 1) {
                $CronItem['status'] = 'error';
                delete_post_meta($postId, '_aiimage_cueword');
            }
            if (isset($apires['msg']) && !empty($apires['msg'])) {
                $CronItem['message'] = $apires['msg'];
            }
        }

        return $CronItem;
    }

    /**
     * 拉取图片生成结果
     */
    public function process_getimage($CronItem, $cronType, $postId)
    {
        // 验证 postId
        if (empty($postId)) {
            $CronItem['status'] = 'error';
            $CronItem['message'] = esc_html__('Invalid parameters [code:003]', 'xhtheme-ai-toolbox');
            return $CronItem;
        }

        $task_id = isset($CronItem['data']['task_id']) ? $CronItem['data']['task_id'] : '';
        if (empty($task_id)) {
            $CronItem['status'] = 'error';
            $CronItem['message'] = esc_html__('Invalid parameters: task_id is missing', 'xhtheme-ai-toolbox');
            return $CronItem;
        }

        $imagePattern = isset($CronItem['data']['pattern']) ? $CronItem['data']['pattern'] : 'default';
        $getImage = $this->imageapi_get($task_id, $imagePattern);

        if ($getImage['success']) {
            $CronItem['status'] = 'success';
            /**
             * 执行后续的图片更新操作
             */
            $postRes = $this->process_post($CronItem, $postId, $getImage['imageUrl'], 'getimage');
            if (is_wp_error($postRes)) {
                $CronItem['status'] = 'error';
                $CronItem['message'] = '[' . $postRes->get_error_code() . '] ' . $postRes->get_error_message();
                $errorData = $postRes->get_error_data();
                $logMessage = '[XHAiimage] postId:' . $postId . ' [' . $postRes->get_error_code() . '] ' . $postRes->get_error_message();
                if (is_array($errorData)) {
                    foreach ($errorData as $key => $value) {
                        $logMessage .= ' - ' . $key . ': ' . $value;
                    }
                }
                xhaitoolbox_log_error($logMessage);
            }
        } else {
            $errorNum = (int) ($CronItem['errornum'] ?? 0) + 1;
            $CronItem['errornum'] = $errorNum;
            $CronItem['status'] = 'error';
            if (isset($getImage['type']) && $getImage['type'] == 2) {
                $CronItem['status'] = 'hold';
            }

            if (isset($getImage['msg']) && !empty($getImage['msg'])) {
                $CronItem['message'] = $getImage['msg'];
            }
        }
        return $CronItem;
    }

    /**
     * 处理文章
     */
    public function process_post($CronItem, $postId, $imageUrl, $cronType = 'getimage')
    {

        try {
            $result = $this->push_postimage($postId, $imageUrl);

            // 检查是否有待机任务进行状态变更
            if (isset($CronItem['data']['config']['taskStatus'])) {
                xh_check_hold_task($cronType, $postId);
            }

            // 自动发布检查
            xh_loop_auto_publish($postId, $CronItem['cron_id'] ?? 0);

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

            return true;
        } catch (\Throwable $e) {
            return new \WP_Error('image-006', __('Processing error', 'xhtheme-ai-toolbox'), [
                'image_url' => $imageUrl,
                'detail'    => $e->getMessage()
            ]);
        }
    }

    /**
     * 下载远程图片、写入媒体库，并按配置应用到文章
     */
    public function push_postimage($post_id, $image_url)
    {
        if (empty($post_id) || empty($image_url)) {
            return new \WP_Error('image-001', __('Invalid parameters', 'xhtheme-ai-toolbox'));
        }

        if (!function_exists('download_url')) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }
        if (!function_exists('media_handle_sideload')) {
            require_once ABSPATH . 'wp-admin/includes/media.php';
            require_once ABSPATH . 'wp-admin/includes/image.php';
        }

        $imageCompress = xh_option('imageCompress', true);
        $old_image_url = $image_url;

        if ($imageCompress) {
            $imageHost = wp_parse_url($image_url, PHP_URL_HOST);
            $compressHost = wp_parse_url(XHTHEME_AI_TOOLBOX_IMAGE_COMPRESS_URL, PHP_URL_HOST);
            if ($imageHost && $compressHost && strtolower($imageHost) === strtolower($compressHost)) {
                $imageCompress = false;
            }
        }

        if ($imageCompress) {
            $image_url = XHTHEME_AI_TOOLBOX_IMAGE_COMPRESS_URL . urlencode($image_url);
        }

        $tmp = download_url($image_url, 60);
        if (is_wp_error($tmp)) {
            // 压缩服务失败时，尝试直接下载原始图片
            if ($imageCompress) {
                $image_url = $old_image_url;
                $tmp = download_url($image_url, 60);
            }
            // 仍然失败，返回 WP_Error
            if (is_wp_error($tmp)) {
                return new \WP_Error('image-002', __('Image download failed', 'xhtheme-ai-toolbox'), [
                    'image_url' => $old_image_url,
                    'compress'  => (int)$imageCompress,
                    'detail'    => $tmp->get_error_message()
                ]);
            }
        }

        $ext = pathinfo($tmp, PATHINFO_EXTENSION);
        if (empty($ext)) {
            $ext  = 'jpg';
            $mime = wp_get_image_mime($tmp);
            if ($mime) {
                $mime_to_ext = [
                    'image/webp' => 'webp',
                    'image/png'  => 'png',
                    'image/jpeg' => 'jpg',
                    'image/gif'  => 'gif',
                    'image/bmp'  => 'bmp',
                ];
                if (isset($mime_to_ext[$mime])) {
                    $ext = $mime_to_ext[$mime];
                }
            }
        }

        $filename = uniqid('aiimg_', true) . '.' . strtolower($ext);
        $file_array = array(
            'name' => $filename,
            'tmp_name' => $tmp
        );

        $attachment_id = media_handle_sideload($file_array, $post_id);
        wp_delete_file($tmp);
        if (is_wp_error($attachment_id)) {
            return new \WP_Error('image-003', __('Failed to save image to media library', 'xhtheme-ai-toolbox'), [
                'image_url' => $old_image_url,
                'detail'    => $attachment_id->get_error_message()
            ]);
        }
        $post_update = $this->handle_image_pattern($post_id, $attachment_id);
        if ($post_update === false) {
            return new \WP_Error('image-004', __('Failed to apply image', 'xhtheme-ai-toolbox'), [
                'attachment_id' => $attachment_id
            ]);
        }
        if (is_wp_error($post_update)) {
            return new \WP_Error('image-005', __('Failed to update post', 'xhtheme-ai-toolbox'), [
                'detail' => $post_update->get_error_message()
            ]);
        }
        return true;
    }

    protected function handle_image_pattern($post_id, $attachment_id)
    {
        $imagePattern = xh_option('imagePattern', 'thumb');
        if ($imagePattern !== 'only') {
            set_post_thumbnail($post_id, $attachment_id);
        }
        $inputImage = false;
        $updatePost = [
            'ID' => $post_id,
            'meta_input' => [
                '_aiimage_status' => -2
            ]
        ];
        if ($imagePattern == 'fill' || $imagePattern == 'only') {
            $mapnumber = (int) xh_option('imageMapnum', 1);
            $post = get_post($post_id);
            if (!$post) {
                return false;
            }
            $content = $post->post_content;
            if (strpos($content, '<img') === false) {
                $image_url = wp_get_attachment_url($attachment_id);
                if (has_blocks($content) || empty(trim($content))) {
                    // 区块编辑器处理
                    $figureHtml = sprintf('<figure class="wp-block-image size-full"><img src="%s" alt="%s" class="wp-image-%s"/></figure>', esc_url($image_url), esc_attr($post->post_title), $attachment_id);
                    $figureBlock = array(
                        'blockName' => 'core/image',
                        'attrs' => [
                            'id' => $attachment_id,
                            'sizeSlug' => 'full',
                            'linkDestination' => 'none'
                        ],
                        'innerBlocks' => [],
                        'innerHTML' => [$figureHtml],
                        'innerContent' => [$figureHtml]
                    );
                    $new_blocks = [];
                    if (empty(trim($content))) {
                        $new_blocks[] = $figureBlock;
                        $inputImage = true;
                    } else {
                        $blocks = parse_blocks($content);
                        $paragraph_count = 0;
                        if (!empty($blocks) && is_array($blocks)) {
                            foreach ($blocks as $block) {
                                $new_blocks[] = $block;
                                if ($block['blockName'] === 'core/paragraph') {
                                    $paragraph_count++;
                                    if ($paragraph_count === $mapnumber) {
                                        $new_blocks[] = $figureBlock;
                                        $inputImage = true;
                                    }
                                }
                            }
                        }


                        if (!$inputImage) {
                            $mapnumber = $paragraph_count > 0 ? $paragraph_count - 1 : 0;
                            if (!$mapnumber) {
                                $new_blocks[] = $figureBlock;
                                $inputImage = true;
                            } else {
                                $paragraph_count = 0;
                                $new_blocks = [];
                                foreach ($blocks as $block) {
                                    $new_blocks[] = $block;
                                    if ($block['blockName'] === 'core/paragraph') {
                                        $paragraph_count++;
                                        if ($paragraph_count === $mapnumber) {
                                            $new_blocks[] = $figureBlock;
                                            $inputImage = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $content = serialize_blocks($new_blocks);
                } else {
                    // 经典编辑器处理
                    $paragraph_count = 0;
                    $new_content = '';
                    $image_html = wp_get_attachment_image($attachment_id, 'full');
                    $image_html = str_replace('alt=""', 'alt="' . esc_attr($post->post_title) . '"', $image_html);
                    if (strpos($content, '<p') !== false) {
                        $paragraphs = explode('<p', $content);
                        foreach ($paragraphs as $index => $paragraph) {
                            if (!empty(trim($paragraph))) {
                                $new_content .= '<p' . $paragraph;
                                $paragraph_count++;

                                if ($paragraph_count === $mapnumber) {
                                    $new_content .= $image_html;
                                    $inputImage = true;
                                }
                            }
                        }
                    } else {
                        $paragraphs = explode("\n", $content);
                        foreach ($paragraphs as $index => $line) {
                            if (!empty(trim($line))) {
                                $new_content .= $line . "\n";
                                $paragraph_count++;
                                if ($paragraph_count === $mapnumber) {
                                    $new_content .= $image_html . "\n";
                                    $inputImage = true;
                                }
                            }
                        }
                    }

                    if (!$inputImage) {
                        $new_content .= $image_html;
                        $inputImage = true;
                    }

                    $content = $new_content;
                }
                $updatePost['post_content'] = $content;
            }
        }

        $postUpdate = wp_update_post($updatePost);
        if (is_wp_error($postUpdate)) {
            return $postUpdate;
        }
        if (!$postUpdate) {
            return false;
        }
        return $postUpdate;
    }

    public function imageapi_get($task_id, $imagePattern = 'default')
    {
        if (empty($task_id)) {
            return ['success' => false, 'msg' => __('Task ID is empty, cannot get image!', 'xhtheme-ai-toolbox')];
        }

        $appid = xh_option('appId');
        if (!$appid) {
            return ['success' => false, 'msg' => __('APPID is empty, cannot continue generation!', 'xhtheme-ai-toolbox')];
        }

        $respapi = wp_remote_post(xh_apiurl(), [
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $appid,
                'Referer' => home_url()
            ],
            'body' => json_encode([
                'type' => 'get-images',
                'backstage' => true,
                'version' => '1.0',
                'timestamp' => time(),
                'args' => [
                    'task_id' => $task_id
                ]
            ]),
            'timeout' => XHTHEME_AI_TOOLBOX_APITIMEOUT,
            'sslverify' => false
        ]);
        if (is_wp_error($respapi)) {
            return ['success' => false, 'msg' => $respapi->get_error_message(), 'type' => 1];
        }
        $body = wp_remote_retrieve_body($respapi);
        $resData = $this->decode_api_json_body($body);
        $resMsg = __('Unknown error, waiting to retry!', 'xhtheme-ai-toolbox');
        $restype = 1;
        if (isset($resData['code'])) {
            switch ($resData['code']) {
                case 0:
                    $aidata = $this->extract_api_aidata($resData);
                    $imageUrl = isset($aidata['imageUrl']) ? $aidata['imageUrl'] : '';
                    if (!empty($imageUrl)) {
                        return ['success' => true, 'msg' => 'success', 'imageUrl' => $imageUrl];
                    }
                    break;
                case 10:
                    return ['success' => false, 'msg' => __('Model task in progress, waiting for next query!', 'xhtheme-ai-toolbox'), 'type' => 2];
                default:
                    if (isset($resData['message']) && !empty($resData['message'])) {
                        $resMsg = esc_html($resData['message']);
                    }
                    if ($resData['code'] == 1) {
                        $restype = 0;
                    }
                    break;
            }
        }
        return ['success' => false, 'msg' => $resMsg, 'type' => $restype];
    }

    /**
     * 智谱创建图片create_pattern_cogview
     */
    public function create_pattern_cogview($prompt, $options = [])
    {
        $aliapikey = xh_option('imageApikey');
        $markText = isset($options['mark']) ? (bool) $options['mark'] : xh_option('imageMark', false);
        if (!$aliapikey) {
            return ['success' => false, 'msg' => __('Please configure the Zhipu Platform API-KEY first!', 'xhtheme-ai-toolbox')];
        }

        // 使用新的模型获取方法
        $model = $this->get_model_code('cogview');
        if (empty($model)) {
            $model = 'cogview-3-flash'; // 默认模型
        }

        // 获取图片尺寸（内部根据模型智能匹配规则）
        $imageSize = !empty($options['size'])
            ? sanitize_text_field($options['size'])
            : $this->get_imagesize($model, 'x');

        $argsBody = [
            'model' => $model,
            'prompt' => $prompt,
            'size' => $imageSize,
            'quality' => 'hd',
            'watermark_enabled' => (bool) $markText
        ];
        $args = array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $aliapikey,
                'Content-Type' => 'application/json'
            ),
            'body' => json_encode($argsBody),
            'timeout' => 120
        );

        $response = wp_remote_post('https://open.bigmodel.cn/api/paas/v4/images/generations', $args);
        if (is_wp_error($response)) {
            return [
                'success' => false,
                'msg' => $response->get_error_message()
            ];
        }
        $body = wp_remote_retrieve_body($response);
        $status_code = wp_remote_retrieve_response_code($response);
        $resData = $this->decode_api_json_body($body);
        if (isset($resData['error']) && is_array($resData['error'])) {
            $errorArr = $resData['error'];
            $errorCode = isset($errorArr['code']) ? $errorArr['code'] : 'unknown';
            $errorMessage = (isset($errorArr['message']) && is_scalar($errorArr['message']) && $errorArr['message'] !== '')
                ? (string) $errorArr['message']
                : ((isset($resData['message']) && is_scalar($resData['message']) && $resData['message'] !== '')
                    ? (string) $resData['message']
                    : __('Unknown error, waiting to retry!', 'xhtheme-ai-toolbox'));
            return [
                'success' => false,
                'msg' => '[' . $errorCode . ']' . $errorMessage,
                'type' => $status_code !== 429 ? 1 : 0
            ];
        }
        if ($status_code == 200 && isset($resData['data']) && is_array($resData['data'])) {
            $imageUrl = isset($resData['data'][0]['url']) ? $resData['data'][0]['url'] : '';
            if (!empty($imageUrl)) {
                return [
                    'success' => true,
                    'notask' => true,
                    'msg' => 'success',
                    'imageUrl' => $imageUrl
                ];
            }
        }
        return [
            'success' => false,
            'msg' => __('Unknown error, waiting to retry!', 'xhtheme-ai-toolbox')
        ];
    }


    public function imageapi_create($prompt, $imagePattern, $options = [])
    {
        if (empty($prompt)) {
            return ['success' => false, 'msg' => __('Image prompt is empty, cannot continue generation!', 'xhtheme-ai-toolbox')];
        }
        switch ($imagePattern) {
            case 'aliyun':
                return $this->create_pattern_aliyun($prompt, $options);
            case 'cogview':
                return $this->create_pattern_cogview($prompt, $options);
        }
        return $this->create_pattern_default($prompt, $options);
    }

    private function create_pattern_default($prompt, $options = [])
    {
        $imageSize = !empty($options['size']) ? sanitize_text_field($options['size']) : $this->get_imagesize('default', 'x');
        $markText = isset($options['mark']) ? (bool) $options['mark'] : xh_option('imageMark', false);
        $imageStyle = !empty($options['style']) ? sanitize_text_field($options['style']) : xh_option('imageStyle', 'auto');
        $scene = !empty($options['scene']) ? sanitize_text_field($options['scene']) : '';
        $apiType = !empty($options['apitype']) ? sanitize_key((string) $options['apitype']) : '';
        $appid = xh_option('appId');
        if (!$appid) {
            return ['success' => false, 'msg' => __('APPID is empty, cannot continue generation!', 'xhtheme-ai-toolbox')];
        }

        $requestArgs = [
            'size' => $imageSize,
            'style' => $imageStyle,
            'mark' => $markText
        ];
        if ($scene !== '') {
            $requestArgs['scene'] = $scene;
        }
        if ($apiType !== '') {
            $requestArgs['apitype'] = $apiType;
        }

        $requestBody = [
            'type' => 'create-images',
            'content' => $prompt,
            'backstage' => true,
            'model' => 'auto',
            'version' => '1.0',
            'timestamp' => time(),
            'args' => $requestArgs
        ];

        $respapi = wp_remote_post(xh_apiurl(), [
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $appid,
                'Referer' => home_url()
            ],
            'body' => wp_json_encode($requestBody),
            'timeout' => XHTHEME_AI_TOOLBOX_APITIMEOUT,
            'sslverify' => false
        ]);
        if (is_wp_error($respapi)) {
            return ['success' => false, 'msg' => $respapi->get_error_message()];
        }
        $body = wp_remote_retrieve_body($respapi);
        $resData = $this->decode_api_json_body($body);
        $restype = 1;
        $resMsg = __('Unknown error, waiting to retry!', 'xhtheme-ai-toolbox');
        if (isset($resData['code'])) {
            switch ($resData['code']) {
                case 0:
                    $aidata = $this->extract_api_aidata($resData);
                    if (isset($aidata['task_id'])) {
                        $task_id = isset($aidata['task_id']) ? $aidata['task_id'] : '';
                        if (!empty($task_id)) {
                            return [
                                'success' => true,
                                'msg' => 'pass',
                                'task_id' => $task_id
                            ];
                        }
                    } elseif (isset($aidata['images'])) {
                        $imageUrl = isset($aidata['images'][0]) ? $aidata['images'][0] : '';
                        if (!empty($imageUrl)) {
                            return [
                                'success' => true,
                                'notask' => true,
                                'msg' => 'pass',
                                'imageUrl' => $imageUrl
                            ];
                        }
                    }
                    break;
                default:
                    if (isset($resData['message']) && !empty($resData['message'])) {
                        $resMsg = esc_html($resData['message']);
                    }
                    if ($resData['code'] == 1) {
                        $restype = 0;
                    }
                    break;
            }
        }

        return [
            'success' => false,
            'msg' => $resMsg,
            'type' => $restype
        ];
    }

    /**
     * 阿里云创建图片（同步接口）
     */
    private function create_pattern_aliyun($prompt, $options = [])
    {
        $aliapikey = xh_option('imageApikey');
        $markText = isset($options['mark']) ? (bool) $options['mark'] : xh_option('imageMark', false);
        if (!$aliapikey) {
            return ['success' => false, 'msg' => __('Please configure the Bailian Platform API-KEY first!', 'xhtheme-ai-toolbox')];
        }

        // 获取模型代码
        $model = $this->get_model_code('aliyun');
        if (empty($model)) {
            $model = 'qwen-image-plus'; // 默认模型
        }

        // 获取图片尺寸
        $imageSize = !empty($options['size'])
            ? str_replace('x', '*', sanitize_text_field($options['size']))
            : $this->get_imagesize($model, '*');

        // 构建请求体（同步接口格式）
        $argsBody = [
            'model' => $model,
            'input' => [
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => [
                            ['text' => $prompt]
                        ]
                    ]
                ]
            ],
            'parameters' => [
                'size' => $imageSize,
                'prompt_extend' => false,
                'watermark' => (bool) $markText
            ],
            'n' => 1
        ];

        $args = [
            'headers' => [
                'Authorization' => 'Bearer ' . $aliapikey,
                'Content-Type' => 'application/json'
            ],
            'body' => json_encode($argsBody),
            'timeout' => 120  // 同步接口需要更长超时
        ];

        // 同步接口端点（根据后台节点配置动态切换）
        $endpoint = $this->get_aliyun_generation_endpoint();
        $response = wp_remote_post($endpoint, $args);

        if (is_wp_error($response)) {
            return ['success' => false, 'msg' => $response->get_error_message(), 'type' => 1];
        }

        $body = wp_remote_retrieve_body($response);
        $status_code = wp_remote_retrieve_response_code($response);
        $resData = $this->decode_api_json_body($body);

        // 错误处理
        if (isset($resData['code']) && isset($resData['message'])) {
            return ['success' => false, 'msg' => '[' . $resData['code'] . '] ' . $resData['message']];
        }

        // 成功获取图片（同步响应格式）
        if ($status_code == 200 && isset($resData['output']['choices'][0]['message']['content'])) {
            $content = $resData['output']['choices'][0]['message']['content'];
            foreach ($content as $item) {
                if (isset($item['image']) && !empty($item['image'])) {
                    return [
                        'success' => true,
                        'notask' => true,  // 关键：标记为同步模式，无需轮询
                        'msg' => 'success',
                        'imageUrl' => $item['image']
                    ];
                }
            }
        }

        return ['success' => false, 'msg' => __('Unknown error, waiting to retry!', 'xhtheme-ai-toolbox'), 'type' => 1];
    }

    public function generate_aiimages($post)
    {
        if (!xh_ismember())
            return;
        $postId = $post->ID;
        $aiimageword = get_post_meta($postId, '_aiimage_cueword', true);
        $aiimage_status = (int) get_post_meta($postId, '_aiimage_status', true);
        if ((!$aiimage_status || ($aiimage_status > 0 && $aiimage_status < 5)) && $aiimageword) {
            $CronItem = xh_cron_getrow('imageword' . '_' . $postId);
            if (!$CronItem) {
                $imagePromptLevel = sanitize_key((string) xh_option('imagePromptLevel', 'safe'));
                if (!in_array($imagePromptLevel, ['safe', 'aggressive'], true)) {
                    $imagePromptLevel = 'safe';
                }
                if (
                    xh_cron_insert($postId, 'imageword', [
                        'style' => xh_option('imageStyle', 'auto'),
                        'size' => xh_option('imageSize', '1280x768'),
                        'imagePromptLevel' => $imagePromptLevel
                    ], 3)
                ) {
                    update_post_meta($postId, '_aiimage_status', -1);
                }
            }
        }
    }
}
