<?php

defined('ABSPATH') || exit;

// 纭繚鐖剁被瀛樺湪
if (!class_exists('HaoZiTeam\\AIPost\\Service\\Features\\RunLog')) {
    require_once __DIR__ . '/RunLog.php';
}

/**
 * 浼樺寲鐗堢殑RunLog绫?- 鍖呭惈鏁版嵁搴撴€ц兘浼樺寲
 */
class RunLogOptimized extends \HaoZiTeam\AIPost\Service\Features\RunLog
{
    /**
     * 鍒涘缓浼樺寲鍚庣殑琛ㄧ粨鏋?     *
     * @return bool 鏄惁鎴愬姛鍒涘缓
     */
    public static function create_optimized_table()
    {
        global $wpdb;
        $table = self::get_table_name();
        $charset_collate = $wpdb->get_charset_collate();
        
        // 浼樺寲鍚庣殑琛ㄧ粨鏋?- 娣诲姞鏇村绱㈠紩鍜屽垎鍖烘敮鎸?
        $sql = "CREATE TABLE IF NOT EXISTS $table (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            post_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
            instruction TEXT NULL,
            title VARCHAR(255) NOT NULL,
            original_title VARCHAR(255) NULL,
            created_at DATETIME NOT NULL,
            status VARCHAR(32) NOT NULL,
            extra TEXT NULL,
            is_rewrite VARCHAR(20) NULL,
            log_level TINYINT DEFAULT 0,
            PRIMARY KEY (id),
            INDEX idx_post_id (post_id),
            INDEX idx_created_at (created_at),
            INDEX idx_status (status),
            INDEX idx_title (title),
            INDEX idx_created_at_status (created_at, status),
            INDEX idx_post_id_status (post_id, status)
        ) $charset_collate;";
        
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
        
        // 妫€鏌ユ槸鍚﹂渶瑕佸崌绾ц〃缁撴瀯
        self::check_table_upgrade();
        
        return true;
    }
    
    /**
     * 妫€鏌ュ苟鍗囩骇琛ㄧ粨鏋?     */
    private static function check_table_upgrade()
    {
        global $wpdb;
        $table = self::get_table_name();
        
        // 妫€鏌ュ鍚堢储寮曟槸鍚﹀瓨鍦?
        $indexes = $wpdb->get_results("SHOW INDEX FROM $table");
        $existing_indexes = [];
        foreach ($indexes as $index) {
            $existing_indexes[] = $index->Key_name;
        }
        
        // 娣诲姞缂哄け鐨勫鍚堢储寮?
        if (!in_array('idx_created_at_status', $existing_indexes)) {
            $wpdb->query("ALTER TABLE $table ADD INDEX idx_created_at_status (created_at, status)");
        }
        
        if (!in_array('idx_post_id_status', $existing_indexes)) {
            $wpdb->query("ALTER TABLE $table ADD INDEX idx_post_id_status (post_id, status)");
        }
    }
    
    /**
     * 娓呯悊鏃ф棩蹇楋紙浼樺寲鐗堬級
     *
     * @param int $days 淇濈暀澶╂暟
     * @return int 娓呯悊鐨勮褰曟暟
     */
    public static function clean_old_logs_optimized($days = 30)
    {
        global $wpdb;
        $table = self::get_table_name();
        
        // 浣跨敤澶嶅悎绱㈠紩浼樺寲鏌ヨ
        $cutoff_date = date('Y-m-d H:i:s', strtotime("-$days days"));
        
        // 浣跨敤绱㈠紩浼樺寲鍒犻櫎
        $sql = $wpdb->prepare(
            "DELETE FROM $table WHERE created_at < %s AND status IN ('completed', 'failed', 'cancelled')",
            $cutoff_date
        );
        
        $result = $wpdb->query($sql);
        return $result !== false ? $result : 0;
    }
    
    /**
     * 鑾峰彇缁熻淇℃伅
     *
     * @return array 缁熻淇℃伅
     */
    public static function get_statistics()
    {
        global $wpdb;
        $table = self::get_table_name();
        
        $stats = [
            'total' => 0,
            'by_status' => [],
            'by_day' => [],
            'performance' => []
        ];
        
        // 鎬昏褰曟暟
        $stats['total'] = (int) $wpdb->get_var("SELECT COUNT(*) FROM $table");
        
        // 鎸夌姸鎬佺粺璁?
        $status_stats = $wpdb->get_results(
            "SELECT status, COUNT(*) as count FROM $table GROUP BY status ORDER BY count DESC"
        );
        
        foreach ($status_stats as $row) {
            $stats['by_status'][$row->status] = (int) $row->count;
        }
        
        // 鏈€杩?澶╃粺璁?
        $recent_stats = $wpdb->get_results(
            "SELECT DATE(created_at) as date, COUNT(*) as count 
             FROM $table 
             WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
             GROUP BY DATE(created_at) 
             ORDER BY date DESC"
        );
        
        foreach ($recent_stats as $row) {
            $stats['by_day'][$row->date] = (int) $row->count;
        }
        
        return $stats;
    }
    
    /**
     * 妫€鏌ヨ〃鎬ц兘
     *
     * @return array 鎬ц兘鏁版嵁
     */
    public static function check_table_performance()
    {
        global $wpdb;
        $table = self::get_table_name();
        
        $performance = [
            'table_size' => 0,
            'index_size' => 0,
            'row_count' => 0,
            'index_usage' => [],
            'query_performance' => []
        ];
        
        // 鑾峰彇琛ㄥぇ灏忎俊鎭紙MySQL锛?
        $table_info = $wpdb->get_row(
            "SELECT 
                data_length as data_size,
                index_length as index_size,
                table_rows as row_count
             FROM information_schema.tables 
             WHERE table_schema = DATABASE() 
               AND table_name = '$table'"
        );
        
        if ($table_info) {
            $performance['table_size'] = round($table_info->data_size / 1024 / 1024, 2); // MB
            $performance['index_size'] = round($table_info->index_size / 1024 / 1024, 2); // MB
            $performance['row_count'] = (int) $table_info->row_count;
        }
        
        // 妫€鏌ョ储寮曚娇鐢ㄦ儏鍐?
        $indexes = $wpdb->get_results("SHOW INDEX FROM $table");
        
        foreach ($indexes as $index) {
            $performance['index_usage'][] = [
                'name' => $index->Key_name,
                'column' => $index->Column_name,
                'unique' => $index->Non_unique == 0,
                'cardinality' => $index->Cardinality
            ];
        }
        
        return $performance;
    }
    
    /**
     * 鏁版嵁搴撳崌绾ф鏌?     *
     * @param string $current_version 褰撳墠鐗堟湰
     */
    public static function check_upgrade($current_version)
    {
        global $wpdb;
        $table = self::get_table_name();
        
        // 妫€鏌ヨ〃鏄惁瀛樺湪
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table'") === $table;
        
        if (!$table_exists) {
            // 琛ㄤ笉瀛樺湪锛屽垱寤轰紭鍖栬〃
            self::create_optimized_table();
        } else {
            // 琛ㄥ瓨鍦紝妫€鏌ユ槸鍚﹂渶瑕佸崌绾?
            self::check_table_upgrade();
        }
        
        // 璁板綍鍗囩骇鏃ュ織
        $upgrade_log = get_option('ai_post_upgrade_log', []);
        
        // 
        $upgrade_log[] = [
            'version' => $current_version,
            'timestamp' => current_time('mysql'),
            'action' => 'check_upgrade',
            'table_exists' => $table_exists
        ];
        
        // 鍙繚鐣欐渶杩?0娆″崌绾ц褰?
        if (count($upgrade_log) > 10) {
            $upgrade_log = array_slice($upgrade_log, -10);
        }
        
        update_option('ai_post_upgrade_log', $upgrade_log);
    }
    
    /**
     * 鎵归噺鎻掑叆鏃ュ織锛堟€ц兘浼樺寲锛?     *
     * @param array $logs 鏃ュ織鏁扮粍
     * @return bool 鏄惁鎴愬姛
     */
    public static function batch_insert($logs)
    {
        if (empty($logs)) {
            return false;
        }
        
        global $wpdb;
        $table = self::get_table_name();
        
        // 鏋勫缓鎵归噺鎻掑叆SQL
        $values = [];
        $placeholders = [];
        $data = [];
        
        foreach ($logs as $log) {
            $placeholders[] = "(%d, %s, %s, %s, %s, %s, %s, %d)";
            $data[] = $log['post_id'] ?? 0;
            $data[] = $log['instruction'] ?? '';
            $data[] = $log['title'] ?? '';
            $data[] = $log['original_title'] ?? '';
            $data[] = current_time('mysql');
            $data[] = $log['status'] ?? 'pending';
            $data[] = isset($log['extra']) ? serialize($log['extra']) : '';
            $data[] = $log['log_level'] ?? 0;
        }
        
        $sql = "INSERT INTO $table 
                (post_id, instruction, title, original_title, created_at, status, extra, log_level) 
                VALUES " . implode(', ', $placeholders);
        
        $result = $wpdb->query($wpdb->prepare($sql, $data));
        return $result !== false;
    }
    
    /**
     * 鍒嗛〉鏌ヨ鏃ュ織锛堟€ц兘浼樺寲锛?     *
     * @param array $args 鏌ヨ鍙傛暟
     * @return array 鏌ヨ缁撴灉
     */
    public static function paginate($args = [])
    {
        global $wpdb;
        $table = self::get_table_name();
        
        $defaults = [
            'page' => 1,
            'per_page' => 20,
            'status' => '',
            'post_id' => 0,
            'start_date' => '',
            'end_date' => '',
            'search' => '',
            'orderby' => 'created_at',
            'order' => 'DESC'
        ];
        
        $args = wp_parse_args($args, $defaults);
        
        // 鏋勫缓WHERE鏉′欢
        $where = ['1=1'];
        $params = [];
        
        if (!empty($args['status'])) {
            $where[] = 'status = %s';
            $params[] = $args['status'];
        }
        
        if (!empty($args['post_id'])) {
            $where[] = 'post_id = %d';
            $params[] = $args['post_id'];
        }
        
        if (!empty($args['start_date'])) {
            $where[] = 'created_at >= %s';
            $params[] = $args['start_date'];
        }
        
        if (!empty($args['end_date'])) {
            $where[] = 'created_at <= %s';
            $params[] = $args['end_date'];
        }
        
        if (!empty($args['search'])) {
            $where[] = '(title LIKE %s OR instruction LIKE %s)';
            $params[] = '%' . $wpdb->esc_like($args['search']) . '%';
            $params[] = '%' . $wpdb->esc_like($args['search']) . '%';
        }
        
        $where_clause = implode(' AND ', $where);
        
        // 璁＄畻鎬绘暟
        $count_sql = "SELECT COUNT(*) FROM $table WHERE $where_clause";
        if (!empty($params)) {
            $count_sql = $wpdb->prepare($count_sql, $params);
        }
        $total = (int) $wpdb->get_var($count_sql);
        
        // 璁＄畻鍒嗛〉
        $offset = ($args['page'] - 1) * $args['per_page'];
        
        // 鏌ヨ鏁版嵁
        $data_sql = "SELECT * FROM $table WHERE $where_clause 
                     ORDER BY {$args['orderby']} {$args['order']} 
                     LIMIT %d OFFSET %d";
        
        $data_params = array_merge($params, [$args['per_page'], $offset]);
        $data_sql = $wpdb->prepare($data_sql, $data_params);
        
        $results = $wpdb->get_results($data_sql);
        
        return [
            'data' => $results,
            'total' => $total,
            'page' => $args['page'],
            'per_page' => $args['per_page'],
            'total_pages' => ceil($total / $args['per_page'])
        ];
    }
    
    /**
     * 鍒嗛〉鏌ヨ鏃ュ織锛堟€ц兘浼樺寲锛?     *
     * @param array $args 鏌ヨ鍙傛暟
     * @return array 鏌ヨ缁撴灉
     */
    public static function get_logs($paged = 1, $per_page = 20)
    {
        global $wpdb;
        $table = self::get_table_name();

        // 鍏兼容鐗堟湰锛氬厑璁镐紶鍏ユ暟缁勫弬鏁?        $args = [];
        if (is_array($paged)) {
            $args = $paged;
        } else {
            $args = [
                'page' => max(1, intval($paged)),
                'per_page' => max(1, intval($per_page)),
            ];
        }
        
        $defaults = [
            'page' => 1,
            'per_page' => 20,
            'status' => '',
            'post_id' => 0,
            'start_date' => '',
            'end_date' => '',
            'search' => '',
            'orderby' => 'created_at',
            'order' => 'DESC'
        ];
        
        $args = wp_parse_args($args, $defaults);
        
        // 鏋勫缓WHERE鏉′欢
        $where = ['1=1'];
        $params = [];
        
        if (!empty($args['status'])) {
            $where[] = 'status = %s';
            $params[] = $args['status'];
        }
        
        if (!empty($args['post_id'])) {
            $where[] = 'post_id = %d';
            $params[] = $args['post_id'];
        }
        
        if (!empty($args['start_date'])) {
            $where[] = 'created_at >= %s';
            $params[] = $args['start_date'];
        }
        
        if (!empty($args['end_date'])) {
            $where[] = 'created_at <= %s';
            $params[] = $args['end_date'];
        }
        
        if (!empty($args['search'])) {
            $where[] = '(title LIKE %s OR instruction LIKE %s)';
            $params[] = '%' . $wpdb->esc_like($args['search']) . '%';
            $params[] = '%' . $wpdb->esc_like($args['search']) . '%';
        }
        
        $where_clause = implode(' AND ', $where);
        
        // 璁＄畻鎬绘暟
        $count_sql = "SELECT COUNT(*) FROM $table WHERE $where_clause";
        if (!empty($params)) {
            $count_sql = $wpdb->prepare($count_sql, $params);
        }
        $total = (int) $wpdb->get_var($count_sql);
        
        // 璁＄畻鍒嗛〉
        $offset = ($args['page'] - 1) * $args['per_page'];
        
        // 鏌ヨ鏁版嵁
        $data_sql = "SELECT * FROM $table WHERE $where_clause 
                     ORDER BY {$args['orderby']} {$args['order']} 
                     LIMIT %d OFFSET %d";
        
        $data_params = array_merge($params, [$args['per_page'], $offset]);
        $data_sql = $wpdb->prepare($data_sql, $data_params);
        
        $rows = $wpdb->get_results($data_sql);
        $pages = ceil($total / $args['per_page']);
        
        return [
            'data' => $rows,
            'total' => $total,
            'pages' => $pages,
            'page' => $args['page'],
            'per_page' => $args['per_page']
        ];
    }
}

if (!class_exists('HaoZiTeam\\AIPost\\Service\\Features\\RunLogOptimized', false)) {
    class_alias('RunLogOptimized', 'HaoZiTeam\\AIPost\\Service\\Features\\RunLogOptimized');
}
