<?php

namespace HaoZiTeam\AIPost\Handler;

defined('ABSPATH') || exit;

use Exception;
use HaoZiTeam\AIPost\Service\Features\RunLog;

class TitleHandler {


    public static function check($post_id, $settings) {


        $post = \get_post($post_id);


        $title = $post->post_title;


        


        // 中文检测（按字节）


        $is_zh = preg_match('/[\x{4e00}-\x{9fa5}]/u', $title);


        $limit = $is_zh ? $settings['zh-title-limit'] : $settings['en-title-limit'];


        $over_limit = $is_zh ? (strlen($title) > $limit) : (mb_strlen($title) > $limit);





        if ($over_limit) {


            // 新增AI改写逻辑 ▼


            if ($settings['title-rewrite-enabled'] ?? false) {


                $new_title = self::rewrite_title($title, $settings, $is_zh);


                if ($new_title) {


                    \wp_update_post([


                        'ID' => $post_id,


                        'post_title' => $new_title,


                        'post_status' => 'publish' // 改写成功则发布


                    ]);


                    global $wpdb;


                    $table_name = $wpdb->prefix . 'ai_post_rewrite_logs';


                    $wpdb->insert($table_name, [


                        'post_id' => $post_id,


                        'original_title' => $title,


                        'new_title' => $new_title,


                        'rewrite_time' => \current_time('mysql'),


                        'created_at' => \current_time('mysql')


                    ]);


                    // 构建标题改写的说明
                    $instruction = $is_zh ? 
                        "请将以下中文标题改写为不超过{$settings['zh-title-limit']}字节的版本" : 
                        "Rewrite this English title under {$settings['en-title-limit']} characters";

                    // 使用RunLog::add方法统一记录日志，避免重复记录
                    \HaoZiTeam\AIPost\Service\Features\RunLog::add(
                        $instruction,
                        $new_title,
                        'publish',
                        'post_id:' . $post_id,
                        'length',
                        0,
                        $title
                    );


                    return true;


                }


            }


            // 新增AI改写逻辑 ▲





            // 检查标题是否重复
            if ($settings['check-duplicate-title'] === 'on' && self::is_duplicate_title($title)) {
                error_log("AI Post Debug: 检测到重复标题，尝试改写: {$title}");
                
                // 记录开始处理日志
                RunLog::add(
                    "重复标题检测", 
                    $title, 
                    'processing', 
                    '', 
                    'duplicate', 
                    1, 
                    $title
                );
                
                // 尝试重写标题
                $new_title = self::rewrite_title($title, $settings, $is_zh);
                
                if ($new_title) {
                    error_log("AI Post Debug: 标题改写成功: {$new_title}");
                    
                    // 记录成功日志
                    RunLog::add(
                        "重复标题改写", 
                        $new_title, 
                        'success', 
                        '', 
                        'duplicate', 
                        0, 
                        $title
                    );
                    
                    return [
                        'title' => $new_title,
                        'changed' => true
                    ];
                } else {
                    error_log("AI Post Debug: 标题改写失败，保留原标题: {$title}");
                    
                    // 记录失败日志
                    RunLog::add(
                        "重复标题改写", 
                        $title, 
                        'error', 
                        '改写失败，保留原标题', 
                        'duplicate', 
                        2, 
                        $title
                    );
                }
            }


            // 原有草稿处理...


            \wp_update_post([


                'ID' => $post_id,


                'post_status' => 'draft'


            ]);


            return false;


        }


        return true;


    }





    private static function rewrite_title($title, $settings, $is_zh) {


        try {


            // 初始化API客户端（参考Base.php逻辑）


            $api = self::init_api_client($settings);


            if (!$api) return false;





            // 从示例标题数组中随机获取一个示例标题


            $custom_examples = $settings['global_tabs']['custom-title-examples'] ?? '';


            $example_titles = array_filter(explode("\n", $custom_examples));


            


            if (empty($example_titles)) {


                $example_titles = [


                    '老师现场提了一个问题，同学的回答亮了',


                    '那些整天熬夜加班的人注意了',


                    '这个小技巧，99%的人都不知道',


                    '掌握这3点，轻松玩转母婴行业私域运营',


                    '我用了2个月，做坏了6次热点营销',


                    '上海和深圳对比，未来你更看好谁?'


                ];


            }


            


            $random_index = array_rand($example_titles);


            $random_title = trim($example_titles[$random_index]);


            


            // 获取适用的最大长度限制


            $max_length = $is_zh ? $settings['zh-title-limit'] : $settings['en-title-limit'];


            


            // 构建改写指令


            if ($is_zh) {


                $instruction = "请将以下中文标题改写为不超过{$max_length}字节的精简版本：\n\"{$title}\"\n"


                    ."要求：\n"


                    ."1. 保留标题的核心主题和关键信息\n"


                    ."2. 精简冗余词汇，但保持原标题的语气和风格\n"


                    ."3. 如果包含数字，尽量保留这些数字\n"


                    ."4. 请参考以下示例标题的风格和结构，包括是否使用疑问句、数字等元素：\n   \"{$random_title}\"\n"


                    ."5. 确保改写后的标题仍然吸引人且有点击欲\n"


                    ."6. 避免使用《》【】()等特殊符号\n"


                    ."7. 直接输出新标题，不要添加额外说明";


            } else {


                $instruction = "Rewrite this English title to be under {$max_length} characters:\n\"{$title}\"\n"


                    ."Requirements:\n"


                    ."1. Preserve core topic and essential keywords\n"


                    ."2. Remove decorative words and unnecessary adverbs\n"


                    ."3. Restructure the phrase to make it more concise and powerful\n"


                    ."4. Reference this example title style and structure: \"{$random_title}\"\n"


                    ."5. Maintain the original appeal and style\n"


                    ."6. Avoid special characters like [], (), {}\n"


                    ."7. Output only the new title without additional explanation";


            }


            


            // 记录开始处理日志


            RunLog::add(


                $instruction, 


                $title, 


                'processing', 


                '', 


                'length', 


                0, 


                $title


            );


            


            $response = $api->ask($instruction);


            $new_title = preg_replace('/^(标题：|Title:)/i', '', $response['answer']);


            


            // 验证新标题长度


            $valid_length = $is_zh ? 


                (strlen($new_title) <= $settings['zh-title-limit']) :


                (mb_strlen($new_title) <= $settings['en-title-limit']);


            


            if ($valid_length) {


                // 记录成功日志


                RunLog::add(


                    $instruction, 


                    trim($new_title), 


                    'success', 


                    '', 


                    'length', 


                    0, 


                    $title


                );


                return trim($new_title);


            } else {


                // 记录失败日志


                RunLog::add(


                    $instruction, 


                    $title, 


                    'error', 


                    '改写后标题长度仍然超过限制', 


                    'length', 


                    1, 


                    $title


                );


                return false;


            }





        } catch (\Exception $e) {


            error_log("标题改写失败: " . $e->getMessage());


            // 记录异常日志


            RunLog::add(


                $instruction ?? '标题改写', 


                $title, 


                'error', 


                $e->getMessage(), 


                'length', 


                2, 


                $title


            );


            return false;


        }


    }





    private static function init_api_client($settings) {


        // 参考Base.php的API初始化逻辑


        $apiServerType = $settings['api-server-type'] ?? 'custom';


        


        if ($apiServerType === 'deepseek') {


            $accounts = $settings['deepseek-accounts'] ?? [];


            $apiServer = $settings['deepseek-api-server'] ?? 'https://api.deepseek.com/v1/';


        } else {


            $accounts = $settings['openai-accounts'] ?? [];


            $apiServer = $settings['openai-api-server'] ?? 'https://sk.slapi.cn/';


        }





        if (empty($accounts)) return null;





        $account = $accounts[array_rand($accounts)];


        $model = $account['model-selection'] ?? ($apiServerType === 'deepseek' ? 'deepseek-chat' : 'gpt-3.5-turbo');





        return new \HaoZiTeam\ChatGPT\V2(


            $account['account-secret-key'] ?? '',


            $apiServer,


            $model,


            null,


            null,


            360,


            $apiServerType === 'deepseek' ? [


                'is_deepseek' => true,


                'headers' => ['Authorization' => 'Bearer '.$account['account-secret-key']]


            ] : []


        );


    }


} 