#!/bin/bash
# MySQL深度检测脚本
# 使用方法: ./mysql_depth_check.sh

MYSQL_PASSWORD="dNrprU&2S"
CONTAINER="umysql"

# 运行时间
UPTIME=$(docker exec $CONTAINER mysql -uroot -p"$MYSQL_PASSWORD" -e "SHOW STATUS LIKE 'Uptime';" 2>&1 | tail -1 | awk '{print $2}')
if [ -n "$UPTIME" ] && [ "$UPTIME" -gt 0 ]; then
    UPTIME_DAYS=$((UPTIME / 86400))
    echo "UPTIME_DAYS:$UPTIME_DAYS"
else
    echo "UPTIME_DAYS:N/A"
fi

# 连接数
THREADS_CONNECTED=$(docker exec $CONTAINER mysql -uroot -p"$MYSQL_PASSWORD" -e "SHOW STATUS LIKE 'Threads_connected';" 2>&1 | tail -1 | awk '{print $2}')
MAX_CONNECTIONS=$(docker exec $CONTAINER mysql -uroot -p"$MYSQL_PASSWORD" -e "SHOW VARIABLES LIKE 'max_connections';" 2>&1 | tail -1 | awk '{print $2}')
if [ -n "$THREADS_CONNECTED" ] && [ -n "$MAX_CONNECTIONS" ] && [ "$MAX_CONNECTIONS" -gt 0 ]; then
    CONN_PERCENT=$(awk "BEGIN {printf \"%.1f\", $THREADS_CONNECTED*100/$MAX_CONNECTIONS}")
    echo "CONNECTIONS:$THREADS_CONNECTED/$MAX_CONNECTIONS/$CONN_PERCENT"
else
    echo "CONNECTIONS:N/A"
fi

# 慢查询
SLOW_QUERIES=$(docker exec $CONTAINER mysql -uroot -p"$MYSQL_PASSWORD" -e "SHOW GLOBAL STATUS LIKE 'Slow_queries';" 2>&1 | tail -1 | awk '{print $2}')
if [ -n "$SLOW_QUERIES" ]; then
    echo "SLOW_QUERIES:$SLOW_QUERIES"
else
    echo "SLOW_QUERIES:0"
fi

# QPS统计
QUESTIONS=$(docker exec $CONTAINER mysql -uroot -p"$MYSQL_PASSWORD" -e "SHOW GLOBAL STATUS LIKE 'Questions';" 2>&1 | tail -1 | awk '{print $2}')
UPTIME=$(docker exec $CONTAINER mysql -uroot -p"$MYSQL_PASSWORD" -e "SHOW STATUS LIKE 'Uptime';" 2>&1 | tail -1 | awk '{print $2}')
if [ -n "$QUESTIONS" ] && [ -n "$UPTIME" ] && [ "$UPTIME" -gt 0 ]; then
    QPS=$(awk "BEGIN {printf \"%.2f\", $QUESTIONS/$UPTIME}")
    echo "QPS:$QPS"
else
    echo "QPS:N/A"
fi

# TPS统计
COM_COMMIT=$(docker exec $CONTAINER mysql -uroot -p"$MYSQL_PASSWORD" -e "SHOW GLOBAL STATUS LIKE 'Com_commit';" 2>&1 | tail -1 | awk '{print $2}')
COM_ROLLBACK=$(docker exec $CONTAINER mysql -uroot -p"$MYSQL_PASSWORD" -e "SHOW GLOBAL STATUS LIKE 'Com_rollback';" 2>&1 | tail -1 | awk '{print $2}')
if [ -n "$COM_COMMIT" ] && [ -n "$COM_ROLLBACK" ] && [ -n "$UPTIME" ] && [ "$UPTIME" -gt 0 ]; then
    TOTAL_TRANS=$((COM_COMMIT + COM_ROLLBACK))
    TPS=$(awk "BEGIN {printf \"%.2f\", $TOTAL_TRANS/$UPTIME}")
    echo "TPS:$TPS"
else
    echo "TPS:N/A"
fi

# 死锁检测
DEADLOCK_OUTPUT=$(docker exec $CONTAINER mysql -uroot -p"$MYSQL_PASSWORD" -e "SHOW GLOBAL STATUS LIKE 'Innodb_deadlocks';" 2>&1 | grep -v Warning)
if [ -n "$DEADLOCK_OUTPUT" ] && [ "$DEADLOCK_OUTPUT" != "" ]; then
    DEADLOCKS=$(echo "$DEADLOCK_OUTPUT" | awk 'NF>=2 {print $2}')
    if [ -z "$DEADLOCKS" ]; then
        DEADLOCKS=0
    fi
else
    DEADLOCKS=0
fi
echo "DEADLOCKS:$DEADLOCKS"

# Buffer Pool命中率
BUFFER_POOL_RESULT=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -e "SELECT (1 - (SELECT variable_value FROM performance_schema.global_status WHERE variable_name = 'Innodb_buffer_pool_reads') / (SELECT variable_value FROM performance_schema.global_status WHERE variable_name = 'Innodb_buffer_pool_read_requests')) * 100 AS hit_ratio;" 2>&1 | grep -v Warning | tail -1)
if [ -n "$BUFFER_POOL_RESULT" ] && [[ "$BUFFER_POOL_RESULT" =~ ^[0-9]+\.?[0-9]*$ ]]; then
    HIT_RATE=$(awk "BEGIN {printf \"%.2f\", $BUFFER_POOL_RESULT}")
    echo "BUFFER_POOL_HIT_RATE:$HIT_RATE"
else
    echo "BUFFER_POOL_HIT_RATE:N/A"
fi

# 表缓存命中率
OPEN_TABLES=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW GLOBAL STATUS LIKE 'Open_tables';" 2>/dev/null | awk '{print $2}')
OPENED_TABLES=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW GLOBAL STATUS LIKE 'Opened_tables';" 2>/dev/null | awk '{print $2}')

# 验证数值
if [[ "$OPEN_TABLES" =~ ^[0-9]+$ ]] && [[ "$OPENED_TABLES" =~ ^[0-9]+$ ]]; then
    if [ "$OPENED_TABLES" -eq 0 ]; then
        # 没有重新打开过表，缓存命中100%
        echo "CACHE_HIT_RATE:100.00"
    elif [ "$OPEN_TABLES" -gt 0 ]; then
        # 表缓存命中率 = Open_tables / (Open_tables + Opened_tables) × 100
        # Opened_tables表示需要重新打开表的次数（缓存未命中）
        TOTAL_OPENS=$((OPEN_TABLES + OPENED_TABLES))
        CACHE_HIT_RATE=$(awk "BEGIN {printf \"%.2f\", ($OPEN_TABLES * 100) / $TOTAL_OPENS}")
        echo "CACHE_HIT_RATE:$CACHE_HIT_RATE"
    else
        echo "CACHE_HIT_RATE:N/A"
    fi
else
    echo "CACHE_HIT_RATE:N/A"
fi

# 当前活跃查询数
ACTIVE_QUERIES=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW PROCESSLIST;" 2>/dev/null | grep -v "Sleep" | grep -v "binlog" | wc -l)
echo "ACTIVE_QUERIES:$ACTIVE_QUERIES"

# Binlog状态
BINLOG_STATUS=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW VARIABLES LIKE 'log_bin';" 2>/dev/null | awk '{print $2}')
if [ "$BINLOG_STATUS" = "ON" ]; then
    BINLOG_COUNT=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW BINARY LOGS;" 2>/dev/null | wc -l)
    echo "BINLOG_STATUS:ON/$BINLOG_COUNT"
else
    echo "BINLOG_STATUS:OFF"
fi

# 表碎片检测 (DATA_FREE > 10MB的表数量)
FRAGMENTED_TABLES=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA NOT IN ('information_schema','performance_schema','mysql','sys') AND DATA_FREE > 10485760;" 2>/dev/null)
if [ -n "$FRAGMENTED_TABLES" ] && [[ "$FRAGMENTED_TABLES" =~ ^[0-9]+$ ]]; then
    echo "FRAGMENTED_TABLES:$FRAGMENTED_TABLES"
else
    echo "FRAGMENTED_TABLES:0"
fi

# 连接错误统计
CONN_ERRORS=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW STATUS LIKE 'Aborted_connects';" 2>/dev/null | awk '{print $2}')
if [ -n "$CONN_ERRORS" ]; then
    echo "CONN_ERRORS:$CONN_ERRORS"
else
    echo "CONN_ERRORS:0"
fi

# InnoDB缓冲池大小
INNODB_BP_SIZE=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW VARIABLES LIKE 'innodb_buffer_pool_size';" 2>/dev/null | awk '{print $2}')
if [ -n "$INNODB_BP_SIZE" ] && [ "$INNODB_BP_SIZE" -gt 0 ]; then
    # 转换为MB
    BP_SIZE_MB=$((INNODB_BP_SIZE / 1024 / 1024))
    echo "INNODB_BP_SIZE:${BP_SIZE_MB}MB"
else
    echo "INNODB_BP_SIZE:N/A"
fi

# 事务状态统计
TRX_ACTIVE=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW STATUS LIKE 'Innodb_trx_active';" 2>/dev/null | awk '{print $2}')
if [ -n "$TRX_ACTIVE" ]; then
    echo "TRX_ACTIVE:$TRX_ACTIVE"
else
    echo "TRX_ACTIVE:0"
fi

# 锁等待检测
LOCK_WAITS=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW STATUS LIKE 'Innodb_row_lock_current_waits';" 2>/dev/null | awk '{print $2}')
if [ -n "$LOCK_WAITS" ]; then
    echo "LOCK_WAITS:$LOCK_WAITS"
else
    echo "LOCK_WAITS:0"
fi

# 连接池分析（Threads_running/Threads_connected）
THREADS_RUNNING=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW STATUS LIKE 'Threads_running';" 2>/dev/null | awk '{print $2}')
THREADS_CONNECTED_NEW=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW STATUS LIKE 'Threads_connected';" 2>/dev/null | awk '{print $2}')
if [ -n "$THREADS_RUNNING" ] && [ -n "$THREADS_CONNECTED_NEW" ] && [ "$THREADS_CONNECTED_NEW" -gt 0 ]; then
    IDLE_CONN=$((THREADS_CONNECTED_NEW - THREADS_RUNNING))
    echo "THREADS_POOL:$THREADS_RUNNING/$THREADS_CONNECTED_NEW/$IDLE_CONN"
else
    echo "THREADS_POOL:N/A"
fi

# InnoDB状态摘要
INNODB_STATUS=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW ENGINE INNODB STATUS\G" 2>/dev/null | grep -E "LATEST DETECTED DEADLOCK|TRANSACTIONS" | wc -l)
echo "INNODB_STATUS:$INNODB_STATUS"

# 临时表使用率
TEMP_TABLES=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW STATUS LIKE 'Created_tmp_disk_tables';" 2>/dev/null | awk '{print $2}')
TEMP_TABLES_TOTAL=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW STATUS LIKE 'Created_tmp_tables';" 2>/dev/null | awk '{print $2}')
if [ -n "$TEMP_TABLES" ] && [ -n "$TEMP_TABLES_TOTAL" ] && [ "$TEMP_TABLES_TOTAL" -gt 0 ]; then
    TEMP_RATE=$(awk "BEGIN {printf \"%.2f\", ($TEMP_TABLES * 100) / $TEMP_TABLES_TOTAL}")
    echo "TEMP_TABLE_RATE:$TEMP_RATE"
else
    echo "TEMP_TABLE_RATE:N/A"
fi

# 数据库总大小(MB)
DB_SIZE=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SELECT ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) FROM information_schema.TABLES WHERE TABLE_SCHEMA NOT IN ('information_schema','performance_schema','mysql','sys');" 2>/dev/null)
if [ -n "$DB_SIZE" ]; then
    echo "DATABASE_SIZE:${DB_SIZE}MB"
else
    echo "DATABASE_SIZE:N/A"
fi

# 表数量统计
TABLE_COUNT=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA NOT IN ('information_schema','performance_schema','mysql','sys') AND TABLE_TYPE='BASE TABLE';" 2>/dev/null)
if [ -n "$TABLE_COUNT" ]; then
    echo "TABLE_COUNT:$TABLE_COUNT"
else
    echo "TABLE_COUNT:0"
fi

# 复制状态
SLAVE_STATUS=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW SLAVE STATUS\G" 2>/dev/null | grep "Slave_IO_Running:" | awk '{print $2}')
if [ "$SLAVE_STATUS" = "Yes" ]; then
    echo "REPLICATION_STATUS:SLAVE"
else
    echo "REPLICATION_STATUS:MASTER"
fi

# Binlog过期时间(天)
BINLOG_EXPIRE=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "SHOW VARIABLES LIKE 'expire_logs_days';" 2>/dev/null | awk '{print $2}')
if [ -n "$BINLOG_EXPIRE" ]; then
    echo "BINLOG_EXPIRE:${BINLOG_EXPIRE}days"
else
    echo "BINLOG_EXPIRE:N/A"
fi

# ========== 高优先级功能补充 ==========

# 当前活跃查询详情 (SHOW PROCESSLIST)
PROCESSLIST_OUTPUT=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -e "SHOW PROCESSLIST;" 2>/dev/null | grep -v "Command" | head -10)
if [ -n "$PROCESSLIST_OUTPUT" ]; then
    # 统计各状态查询数量
    SLEEP_COUNT=$(echo "$PROCESSLIST_OUTPUT" | grep -c "Sleep" || echo "0")
    QUERY_COUNT=$(echo "$PROCESSLIST_OUTPUT" | grep -v "Sleep" | wc -l)
    LONG_QUERY_COUNT=$(echo "$PROCESSLIST_OUTPUT" | awk -F'\t' '{if ($6>5) print}' | wc -l)

    echo "ACTIVE_PROCESSLIST:Sleep:${SLEEP_COUNT},Active:${QUERY_COUNT},LongRunning:${LONG_QUERY_COUNT}"

    # 输出TOP5耗时查询
    LONG_QUERIES=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -e "SELECT ID, USER, HOST, DB, COMMAND, TIME, STATE, LEFT(INFO, 50) AS QUERY FROM information_schema.PROCESSLIST WHERE COMMAND != 'Sleep' AND TIME > 0 ORDER BY TIME DESC LIMIT 5;" 2>/dev/null | grep -v "QUERY")
    if [ -n "$LONG_QUERIES" ]; then
        echo "LONG_QUERIES_TOP5:$(echo "$LONG_QUERIES" | head -5 | tr '\n' '|' | sed 's/|$//')"
    else
        echo "LONG_QUERIES_TOP5:N/A"
    fi
else
    echo "ACTIVE_PROCESSLIST:N/A"
    echo "LONG_QUERIES_TOP5:N/A"
fi

# 缺少索引的高耗时查询 (通过performance_schema)
SLOW_QUERY_STATS=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -e "
SELECT
    COUNT_STAR as exec_count,
    ROUND(SUM_TIMER_WAIT/1000000000, 2) as total_time_sec,
    ROUND(AVG_TIMER_WAIT/1000000000, 2) as avg_time_sec,
    ROUND(SUM_LOCK_TIME/1000000000, 2) as lock_time_sec,
    digest_text as query_sample
FROM performance_schema.events_statements_summary_by_digest
WHERE digest_text IS NOT NULL
  AND digest_text NOT LIKE '%performance_schema%'
  AND COUNT_STAR > 10
  AND SUM_TIMER_WAIT > 1000000000
ORDER BY SUM_TIMER_WAIT DESC
LIMIT 10;
" 2>/dev/null | grep -v "query_sample")

if [ -n "$SLOW_QUERY_STATS" ]; then
    # 输出TOP1耗时查询的统计
    TOP_QUERY=$(echo "$SLOW_QUERY_STATS" | head -2 | tail -1)
    if [ -n "$TOP_QUERY" ]; then
        EXEC_COUNT=$(echo "$TOP_QUERY" | awk '{print $1}')
        TOTAL_TIME=$(echo "$TOP_QUERY" | awk '{print $2}')
        AVG_TIME=$(echo "$TOP_QUERY" | awk '{print $3}')
        LOCK_TIME=$(echo "$TOP_QUERY" | awk '{print $4}')
        echo "SLOW_QUERY_TOP1:Exec:${EXEC_COUNT},TotalTime:${TOTAL_TIME}s,AvgTime:${AVG_TIME}s,LockTime:${LOCK_TIME}s"
    else
        echo "SLOW_QUERY_TOP1:N/A"
    fi
else
    echo "SLOW_QUERY_TOP1:N/A"
fi

# 缺少索引的表检测
MISSING_INDEX_TABLES=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -e "
SELECT
    t.table_schema,
    t.table_name,
    t.table_rows,
    ROUND(t.data_length / 1024 / 1024, 2) as data_mb
FROM information_schema.TABLES t
WHERE t.table_schema NOT IN ('information_schema','performance_schema','mysql','sys')
  AND NOT EXISTS (
      SELECT 1 FROM information_schema.STATISTICS s
      WHERE s.table_schema = t.table_schema
        AND s.table_name = t.table_name
  )
  AND t.table_rows > 1000
ORDER BY t.data_length DESC
LIMIT 5;
" 2>/dev/null | grep -v "data_mb")

if [ -n "$MISSING_INDEX_TABLES" ]; then
    MISSING_COUNT=$(echo "$MISSING_INDEX_TABLES" | wc -l)
    echo "TABLES_WITHOUT_INDEX:$MISSING_COUNT"
else
    echo "TABLES_WITHOUT_INDEX:0"
fi

# ========== 中优先级功能补充 ==========

# 数据库列表详细输出
DATABASE_LIST=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "
SELECT
    table_schema,
    ROUND(sum(data_length + index_length) / 1024 / 1024, 2) as size_mb
FROM information_schema.tables
WHERE table_schema NOT IN ('information_schema','performance_schema','mysql','sys')
GROUP BY table_schema
ORDER BY size_mb DESC
LIMIT 10;
" 2>&1 | grep -v "\[Warning\]")

if [ -n "$DATABASE_LIST" ]; then
    DB_COUNT=$(echo "$DATABASE_LIST" | wc -l)
    TOTAL_SIZE=$(echo "$DATABASE_LIST" | awk -F'\t' '{sum+=$2} END {printf "%.2f", sum}')
    DB_NAMES=$(echo "$DATABASE_LIST" | awk -F'\t' '{print $1}' | tr '\n' ',' | sed 's/,$//')
    echo "DATABASE_LIST:Count:${DB_COUNT},TotalSize:${TOTAL_SIZE}MB,Databases:${DB_NAMES}"
else
    echo "DATABASE_LIST:N/A"
fi

# InnoDB状态详情 (事务历史)
INNODB_TRX_INFO=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "
SELECT
    COUNT(*) as trx_count,
    IFNULL(SUM(TIMESTAMPDIFF(SECOND, trx_started, NOW())), 0) as total_trx_time
FROM information_schema.INNODB_TRX;
" 2>/dev/null)

if [ -n "$INNODB_TRX_INFO" ]; then
    TRX_COUNT=$(echo "$INNODB_TRX_INFO" | awk -F'\t' '{print $1}')
    TOTAL_TRX_TIME=$(echo "$INNODB_TRX_INFO" | awk -F'\t' '{print $2}')
    echo "INNODB_TRX_DETAIL:Count:${TRX_COUNT},TotalTime:${TOTAL_TRX_TIME}s"
else
    echo "INNODB_TRX_DETAIL:Count:0,TotalTime:0s"
fi

# 表统计 (ubains库TOP20)
UBAINS_TOP_TABLES=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -e "
SELECT
    table_name,
    table_rows,
    round(data_length / 1024 / 1024, 2) as data_mb,
    round(index_length / 1024 / 1024, 2) as index_mb,
    round((data_length + index_length) / 1024 / 1024, 2) as total_mb
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'ubains'
ORDER BY (data_length + index_length) DESC
LIMIT 20;
" 2>/dev/null | grep -v "total_mb")

if [ -n "$UBAINS_TOP_TABLES" ]; then
    TABLE_COUNT=$(echo "$UBAINS_TOP_TABLES" | wc -l)
    # 获取TOP1表的信息
    TOP1_TABLE=$(echo "$UBAINS_TOP_TABLES" | head -2 | tail -1)
    if [ -n "$TOP1_TABLE" ]; then
        TOP1_NAME=$(echo "$TOP1_TABLE" | awk '{print $1}')
        TOP1_SIZE=$(echo "$TOP1_TABLE" | awk '{print $5}')
        echo "UBAINS_TABLES_TOP20:Count:${TABLE_COUNT},Top1:${TOP1_NAME}:${TOP1_SIZE}MB"
    else
        echo "UBAINS_TABLES_TOP20:Count:${TABLE_COUNT}"
    fi
else
    echo "UBAINS_TABLES_TOP20:N/A"
fi

# 复制状态详情
SLAVE_STATUS_DETAIL=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -e "SHOW SLAVE STATUS\G" 2>/dev/null)
if [ -n "$SLAVE_STATUS_DETAIL" ]; then
    # 提取关键复制状态信息
    SLAVE_IO=$(echo "$SLAVE_STATUS_DETAIL" | grep "Slave_IO_Running:" | awk '{print $2}')
    SLAVE_SQL=$(echo "$SLAVE_STATUS_DETAIL" | grep "Slave_SQL_Running:" | awk '{print $2}')
    BEHIND_MASTER=$(echo "$SLAVE_STATUS_DETAIL" | grep "Seconds_Behind_Master:" | awk '{print $2}')

    if [ "$SLAVE_IO" = "Yes" ]; then
        echo "REPLICATION_DETAIL:IO:$SLAVE_IO,SQL:$SLAVE_SQL,Delay:${BEHIND_MASTER}s"
    else
        echo "REPLICATION_DETAIL:MASTER"
    fi
else
    echo "REPLICATION_DETAIL:MASTER"
fi

# 连接错误详细统计 - 该功能依赖的表在当前MySQL版本中不存在，已移除
# 使用基础的Aborted_connects统计即可（CONN_ERRORS变量）

# ========== 补充：InnoDB缓冲池详情 ==========
INNODB_BP_DETAIL=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -e "SHOW ENGINE INNODB STATUS\G" 2>/dev/null | grep -A 20 "Buffer pool hit rate")
if [ -n "$INNODB_BP_DETAIL" ]; then
    BP_HIT_RATE=$(echo "$INNODB_BP_DETAIL" | grep -oP 'hit rate \K[\d/]+' | head -1)
    if [ -n "$BP_HIT_RATE" ]; then
        echo "INNODB_BP_DETAIL:HitRate:${BP_HIT_RATE}"
    else
        echo "INNODB_BP_DETAIL:N/A"
    fi
else
    echo "INNODB_BP_DETAIL:N/A"
fi

# ========== 补充：锁信息详情 ==========
LOCK_INFO=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "
SELECT
    COUNT(*) as lock_waits,
    IFNULL(SUM(TIMESTAMPDIFF(SECOND, r.trx_started, NOW())), 0) as total_wait_time
FROM information_schema.INNODB_LOCK_WAITS w
JOIN information_schema.INNODB_TRX r ON r.trx_id = w.requesting_trx_id;
" 2>/dev/null)

if [ -n "$LOCK_INFO" ]; then
    LOCK_COUNT=$(echo "$LOCK_INFO" | awk -F'\t' '{print $1}')
    WAIT_TIME=$(echo "$LOCK_INFO" | awk -F'\t' '{print $2}')
    echo "LOCK_DETAIL:Waits:${LOCK_COUNT},TotalWait:${WAIT_TIME}s"
else
    echo "LOCK_DETAIL:Waits:0,TotalWait:0s"
fi

# ========== 补充：表碎片检测详情 ==========
FRAGMENTED_TABLES_DETAIL=$(docker exec -e MYSQL_PWD="$MYSQL_PASSWORD" $CONTAINER mysql -uroot -N -e "
SELECT
    CONCAT(table_schema, '.', table_name) as table_name,
    ROUND(data_length / 1024 / 1024, 2) as data_mb,
    ROUND(data_free / 1024 / 1024, 2) as fragment_mb
FROM information_schema.TABLES
WHERE TABLE_SCHEMA NOT IN ('information_schema','performance_schema','mysql','sys')
  AND DATA_FREE > 10485760
ORDER BY data_free DESC
LIMIT 5;
" 2>/dev/null | grep -v "fragment_mb")

if [ -n "$FRAGMENTED_TABLES_DETAIL" ]; then
    FRAG_COUNT=$(echo "$FRAGMENTED_TABLES_DETAIL" | wc -l)
    TOP_FRAG=$(echo "$FRAGMENTED_TABLES_DETAIL" | head -1)
    if [ -n "$TOP_FRAG" ]; then
        TABLE_NAME=$(echo "$TOP_FRAG" | awk '{print $1}')
        FRAG_MB=$(echo "$TOP_FRAG" | awk '{print $3}')
        echo "FRAGMENTED_DETAIL:Count:${FRAG_COUNT},Top1:${TABLE_NAME}:${FRAG_MB}MB"
    else
        echo "FRAGMENTED_DETAIL:Count:${FRAG_COUNT}"
    fi
else
    echo "FRAGMENTED_DETAIL:Count:0"
fi
