<?php

/**
 * Plugin Name: 极光AI
 * Plugin URI: https://www.2090ai.cn
 * Description: 使用AI全自动生成文章，彻底解放双手。即使你在泡澡，AI也会为你的站点不间断发布文章。开始使用：1、激活插件；2、面板配置API和KEY；3、添加任务。
 * Author: lex
 * Author URI: https://www.2090ai.cn
 * Version: 2.9.0
 * License: GPLv3 or later
 * Text Domain: ai-post
 * Network: true
 */

namespace HaoZiTeam\AIPost;

use YahnisElsts\PluginUpdateChecker\v5\PucFactory;

// ==================== 优化功能开始 ====================

if (!defined('PLUGIN_FILE')) {
    define('PLUGIN_FILE', __FILE__);
}
if (!defined('HAOZI_AIPOST_VERSION')) {
    define('HAOZI_AIPOST_VERSION', '2.9.0');
}
if (!defined('AIPOST_PLUGIN_PATH')) {
    define('AIPOST_PLUGIN_PATH', plugin_dir_path(__FILE__));
}

if (file_exists(__DIR__ . '/vendor/autoload.php')) {
    require_once __DIR__ . '/vendor/autoload.php';
}

if (file_exists(__DIR__ . '/Inc/cgps-framework/cgps-framework.php')) {
    require_once __DIR__ . '/Inc/cgps-framework/cgps-framework.php';
}

if (file_exists(__DIR__ . '/Inc/class-article-with-pictures-api.php')) {
    require_once __DIR__ . '/Inc/class-article-with-pictures-api.php';
}

if (file_exists(__DIR__ . '/Service/Features/EditorGenerateUI.php')) {
    require_once __DIR__ . '/Service/Features/EditorGenerateUI.php';
}

if (file_exists(__DIR__ . '/Service/Features/PriorityQueue.php')) {
    require_once __DIR__ . '/Service/Features/PriorityQueue.php';
}

if (file_exists(__DIR__ . '/Service/Features/EditorGenerateEndpoint.php')) {
    require_once __DIR__ . '/Service/Features/EditorGenerateEndpoint.php';
}

if (file_exists(__DIR__ . '/Service/Features/AdminChatTables.php')) {
    require_once __DIR__ . '/Service/Features/AdminChatTables.php';
}

if (file_exists(__DIR__ . '/Service/Features/AdminChatEndpoint.php')) {
    require_once __DIR__ . '/Service/Features/AdminChatEndpoint.php';
}

if (file_exists(__DIR__ . '/Service/Features/AdminChatStreamAjax.php')) {
    require_once __DIR__ . '/Service/Features/AdminChatStreamAjax.php';
}

// 更新检测（从远端 update.json 获取新版本信息）
if (file_exists(__DIR__ . '/vendor/yahnis-elsts/plugin-update-checker/plugin-update-checker.php')) {
    require_once __DIR__ . '/vendor/yahnis-elsts/plugin-update-checker/plugin-update-checker.php';
    if (class_exists('YahnisElsts\\PluginUpdateChecker\\v5\\PucFactory')) {
        try {
            $MyUpdateChecker = PucFactory::buildUpdateChecker(
                'https://version.suqianweb.cn/update.json',
                __FILE__,
                'ai-post'
            );
            $MyUpdateChecker->addResultFilter(function ($info) {
                if (isset($info->version)) {
                    \update_option('ai_post_latest_version', $info->version);
                }
                return $info;
            });
        } catch (\Throwable $e) {
            // 忽略更新检测异常，避免影响插件主流程
        }
    }
}

// 注册激活钩子（优化版）
\register_activation_hook(__FILE__, 'HaoZiTeam\AIPost\activate_plugin_optimized');
function activate_plugin_optimized() {
    // 防止激活流程中任何文件意外输出（BOM/空白/echo），导致“headers already sent”
    $aipost_ob_level = \ob_get_level();
    \ob_start();
    try {
    require_once \plugin_dir_path(__FILE__) . 'includes/Activator.php';
    \AIPostActivator::activate();

    // 新增：创建运行日志表（优化版）
    if (file_exists(\plugin_dir_path(__FILE__) . 'Service/Features/RunLogOptimized.php')) {
        require_once \plugin_dir_path(__FILE__) . 'Service/Features/RunLogOptimized.php';
        \HaoZiTeam\AIPost\Service\Features\RunLogOptimized::create_optimized_table();
    }

    // 新增：创建安妮聊天相关自定义表
    if (class_exists('HaoZiTeam\\AIPost\\Service\\Features\\AdminChatTables')) {
        \HaoZiTeam\AIPost\Service\Features\AdminChatTables::create_tables();
    }
    
    // 初始化缓存管理器
    if (file_exists(\plugin_dir_path(__FILE__) . 'Service/Features/CacheManager.php')) {
        require_once \plugin_dir_path(__FILE__) . 'Service/Features/CacheManager.php';
        $cache_manager = \HaoZiTeam\AIPost\Service\Features\CacheManager::get_instance();
    }
    
    // 注册异常处理
    if (file_exists(\plugin_dir_path(__FILE__) . 'Service/Features/ExceptionHandler.php')) {
        require_once \plugin_dir_path(__FILE__) . 'Service/Features/ExceptionHandler.php';
        if (\class_exists('HaoZiTeam\\AIPost\\Service\\Features\\ExceptionHandler')) {
            if (\method_exists('HaoZiTeam\\AIPost\\Service\\Features\\ExceptionHandler', 'register_handlers')) {
                \HaoZiTeam\AIPost\Service\Features\ExceptionHandler::register_handlers();
            } elseif (\method_exists('HaoZiTeam\\AIPost\\Service\\Features\\ExceptionHandler', 'register')) {
                \HaoZiTeam\AIPost\Service\Features\ExceptionHandler::register();
            }
        }
    }
    
    // 新增定时任务
    if (!wp_next_scheduled('ai_post_cleanup_logs')) {
        wp_schedule_event(time(), 'daily', 'ai_post_cleanup_logs');
    }
    if (!wp_next_scheduled('ai_post_cleanup_cache')) {
        wp_schedule_event(time(), 'weekly', 'ai_post_cleanup_cache');
    }
    if (!wp_next_scheduled('ai_post_monitor_performance')) {
        wp_schedule_event(time(), 'hourly', 'ai_post_monitor_performance');
    }
    } finally {
        $aipost_out = '';
        while (\ob_get_level() > $aipost_ob_level) {
            $aipost_out = \ob_get_clean() . $aipost_out;
        }
        if ($aipost_out !== '') {
            \error_log('[AI-Post][Activate] unexpected output length=' . \strlen($aipost_out));
        }
    }
}

// 注册停用钩子（优化版）
\register_deactivation_hook(__FILE__, 'HaoZiTeam\AIPost\deactivate_plugin_optimized');
function deactivate_plugin_optimized() {
    $deactivator = \plugin_dir_path(__FILE__) . 'includes/Deactivator.php';
    if (file_exists($deactivator)) {
        require_once $deactivator;
        if (class_exists('AIPostDeactivator') && method_exists('AIPostDeactivator', 'deactivate')) {
            \AIPostDeactivator::deactivate();
        }
    }
    
    // 清理定时任务
    wp_clear_scheduled_hook('ai_post_cleanup_logs');
    wp_clear_scheduled_hook('ai_post_cleanup_cache');
    wp_clear_scheduled_hook('ai_post_monitor_performance');
    
    // 清理缓存
    if (file_exists(\plugin_dir_path(__FILE__) . 'Service/Features/CacheManager.php')) {
        require_once \plugin_dir_path(__FILE__) . 'Service/Features/CacheManager.php';
        $cache_manager = \HaoZiTeam\AIPost\Service\Features\CacheManager::get_instance();
        if (method_exists($cache_manager, 'clear_all')) {
            $cache_manager->clear_all();
        } elseif (method_exists($cache_manager, 'clear')) {
            $cache_manager->clear();
        }
    }
}

// 数据库版本检查和升级
function check_db_version_and_upgrade() {
    $current_version = get_option('ai_post_db_version', '0');
    $target_version = '2.9.0';
    
    if (version_compare($current_version, $target_version, '<')) {
        // 运行数据库升级
        if (file_exists(\plugin_dir_path(__FILE__) . 'Service/Features/RunLogOptimized.php')) {
            require_once \plugin_dir_path(__FILE__) . 'Service/Features/RunLogOptimized.php';
            \HaoZiTeam\AIPost\Service\Features\RunLogOptimized::create_optimized_table();
        }

        // 运行数据库升级：安妮聊天相关自定义表
        if (class_exists('HaoZiTeam\\AIPost\\Service\\Features\\AdminChatTables')) {
            \HaoZiTeam\AIPost\Service\Features\AdminChatTables::create_tables();
        }
        
        update_option('ai_post_db_version', $target_version);
    }
}
// 升级检查：后台访问与插件加载时都触发一次（避免仅后台某些页面才触发升级）
\add_action('admin_init', 'HaoZiTeam\AIPost\check_db_version_and_upgrade');
\add_action('plugins_loaded', 'HaoZiTeam\AIPost\check_db_version_and_upgrade');

// 安妮聊天：注册 REST API 路由
if (class_exists('HaoZiTeam\\AIPost\\Service\\Features\\AdminChatEndpoint')) {
    \HaoZiTeam\AIPost\Service\Features\AdminChatEndpoint::register();
}

if (file_exists(__DIR__ . '/Service/Features/CronEndpoint.php')) {
    require_once __DIR__ . '/Service/Features/CronEndpoint.php';
}

if (file_exists(__DIR__ . '/Service/Features/SettingsEndpoint.php')) {
    require_once __DIR__ . '/Service/Features/SettingsEndpoint.php';
}

// 安妮聊天：注册 admin-ajax 流式输出入口
if (class_exists('HaoZiTeam\\AIPost\\Service\\Features\\AdminChatStreamAjax')) {
    \HaoZiTeam\AIPost\Service\Features\AdminChatStreamAjax::register();
}

// 定时任务回调函数
function cleanup_logs_callback() {
    if (file_exists(\plugin_dir_path(__FILE__) . 'Service/Features/RunLogOptimized.php')) {
        require_once \plugin_dir_path(__FILE__) . 'Service/Features/RunLogOptimized.php';
        if (\class_exists('HaoZiTeam\\AIPost\\Service\\Features\\RunLogOptimized')) {
            if (\method_exists('HaoZiTeam\\AIPost\\Service\\Features\\RunLogOptimized', 'cleanup_old_logs')) {
                \HaoZiTeam\AIPost\Service\Features\RunLogOptimized::cleanup_old_logs();
            } elseif (\method_exists('HaoZiTeam\\AIPost\\Service\\Features\\RunLogOptimized', 'clean_old_logs_optimized')) {
                // 默认保留天数：跟随原插件的配置项（没有则 30 天）
                $days = (int) \get_option('ai_post_log_retention_days', 30);
                \HaoZiTeam\AIPost\Service\Features\RunLogOptimized::clean_old_logs_optimized($days);
            }
        }
    }
}
\add_action('ai_post_cleanup_logs', 'HaoZiTeam\AIPost\cleanup_logs_callback');

function cleanup_cache_callback() {
    if (file_exists(\plugin_dir_path(__FILE__) . 'Service/Features/CacheManager.php')) {
        require_once \plugin_dir_path(__FILE__) . 'Service/Features/CacheManager.php';
        $cache_manager = \HaoZiTeam\AIPost\Service\Features\CacheManager::get_instance();
        if (\method_exists($cache_manager, 'clear_all')) {
            $cache_manager->clear_all();
        } elseif (\method_exists($cache_manager, 'clear')) {
            $cache_manager->clear();
        }
    }
}
\add_action('ai_post_cleanup_cache', 'HaoZiTeam\AIPost\cleanup_cache_callback');

function monitor_performance_callback() {
    if (file_exists(\plugin_dir_path(__FILE__) . 'Service/Features/RunLogOptimized.php')) {
        require_once \plugin_dir_path(__FILE__) . 'Service/Features/RunLogOptimized.php';
        $performance_data = null;
        if (\class_exists('HaoZiTeam\\AIPost\\Service\\Features\\RunLogOptimized')) {
            if (\method_exists('HaoZiTeam\\AIPost\\Service\\Features\\RunLogOptimized', 'get_performance_stats')) {
                $performance_data = \HaoZiTeam\AIPost\Service\Features\RunLogOptimized::get_performance_stats();
            } elseif (\method_exists('HaoZiTeam\\AIPost\\Service\\Features\\RunLogOptimized', 'check_table_performance')) {
                $performance_data = \HaoZiTeam\AIPost\Service\Features\RunLogOptimized::check_table_performance();
            }
        }
        
        // 可以在这里添加性能监控逻辑
        // 例如：发送警报、记录性能数据等
    }
}
\add_action('ai_post_monitor_performance', 'HaoZiTeam\AIPost\monitor_performance_callback');

// 修复运行日志表（在管理页面访问时执行）
function fix_runlog_table() {
    if (file_exists(\plugin_dir_path(__FILE__) . 'Service/Features/RunLogOptimized.php')) {
        require_once \plugin_dir_path(__FILE__) . 'Service/Features/RunLogOptimized.php';
        \HaoZiTeam\AIPost\Service\Features\RunLogOptimized::repair_log_table();
    }
}

// 在WordPress初始化时检查并修复
\add_action('admin_init', function() {
    // 仅在管理员访问插件设置页面时执行
    if (isset($_GET['page']) && $_GET['page'] === 'ai-post' && isset($_GET['tab']) && $_GET['tab'] === 'log') {
        \HaoZiTeam\AIPost\fix_runlog_table();
    }
});

function load_admin_styles() {
    $css_rel = 'assets/css/admin.css';
    $css_abs = __DIR__ . '/' . $css_rel;
    if (file_exists($css_abs)) {
        wp_enqueue_style('ai-post-admin', plugin_dir_url(__FILE__) . $css_rel, [], '2.9.0');
    }
}
\add_action('admin_enqueue_scripts', 'HaoZiTeam\AIPost\load_admin_styles');

// 网络管理员菜单 - 修复第219行附近的语法错误
function add_network_admin_menu() {
    add_menu_page(
        '极光AI设置',           // 页面标题
        '极光AI',               // 菜单标题
        'manage_network_options', // 权限
        'ai-post',              // 菜单slug
        'HaoZiTeam\AIPost\network_admin_page', // 回调函数
        'dashicons-admin-post', // 图标
        30                      // 位置
    );
}
\add_action('network_admin_menu', 'HaoZiTeam\AIPost\add_network_admin_menu');

function network_admin_page() {
    require_once plugin_dir_path(__FILE__) . 'admin/NetworkAdmin.php';
}

// 渲染YouTube iframe到内容中
function render_youtube_iframe_in_content($content) {
    $callback = function($matches) {
        $wrapper_style = 'position:relative;padding-bottom:56.25%;height:0;overflow:hidden;max-width:100%;';
        $iframe_style = 'position:absolute;top:0;left:0;width:100%;height:100%;border:0;';

        $full_div = isset($matches[0]) ? (string)$matches[0] : '';
        $src_raw = isset($matches[1]) ? (string)$matches[1] : '';
        $iframe_id = isset($matches[2]) ? (string)$matches[2] : '';

        $src_raw = html_entity_decode($src_raw, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $src_raw = trim($src_raw);

        if ($src_raw === '') {
            return $full_div;
        }

        $src_attr = esc_url($src_raw);
        if ($src_attr === '') {
            return $full_div;
        }

        $id_attr = '';
        $iframe_id = trim($iframe_id);
        if ($iframe_id !== '') {
            $id_attr = preg_replace('/[^a-zA-Z0-9_\-:]/', '', $iframe_id);
        }

        $iframe_html = '<div class="tl_youtube_video_wrapper" style="' . $wrapper_style . '"><iframe'
            . ($id_attr !== '' ? ' id="' . esc_attr($id_attr) . '"' : '')
            . ' src="' . $src_attr . '" style="' . $iframe_style . '" allowfullscreen></iframe></div>';

        return $iframe_html;
    };

    return preg_replace_callback(
        '/<div[^>]*class="[^\"]*tl_youtube_video_wrapper[^\"]*"[^>]*data-youtube-src="([^"]+)"[^>]*?(?:data-iframe-id="([^"]+)")?[^>]*>\s*<\/div>/is',
        $callback,
        $content
    );
}

\add_filter('the_content', 'HaoZiTeam\AIPost\render_youtube_iframe_in_content');

if (file_exists(__DIR__ . '/Plugin.php')) {
    require_once __DIR__ . '/Plugin.php';
}

new Plugin();