#!/system/bin/sh
# 解决序号显示错乱、选择无效的核心修复版
SCRIPT_PATH=$(readlink -f "$0")
SCRIPT_DIR=$(dirname "$SCRIPT_PATH")
OUTPUT_FOLDER="${SCRIPT_DIR}/输出文件"
LOADINGBG_FOLDER="/storage/emulated/0/Android/data/com.tencent.tmgp.pubgmhd/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/ImageDownloadV3/LoadingBG"

# 目标文件列表（固定61个）
TARGET_ALL=(
    "139f7ca4602884c210afd4193459d03b" "33b643f557f43d5b254340100d981d10" "350eef5300f19b90cb99babf6d97b038"
    "6800fb237e5eb16cd726bb9201b07051" "6f1f2da5655591f3e414f9cb2f637364" "8450181c81be27e448abc8b2eb24b49b"
    "9bb41bcd562fb5e08f8efbf064957d60" "d1f95cf4b3f8990d8b0444575a1fbb61" "dc9de740a5e4939f041c7c33fe6e5abd"
    "2b3ee26822e44e9ee5fae90181d534d3" "33d6d44faa806c43197c2a92aabc7460" "59f95ac8c3555e4af9ef92cd881f0612"
    "6e0156c739f31797a89122c009afb3fb" "711e059443369ce055b46dc56f9cf40a" "864f05443816f3c3f9aa9b0fdceb7f38"
    "a26516845498fc100bbc825b7b68af7c" "bdb5cb02a2256317c81129c65d9e417b" "de97370724f88a85edd5866d2c3182c3"
    "ffc29f7b097133e8f3d39ee61269cb91" "1307d8cb164b1716150b1193661d419e" "43c0dd62e8ff2873ab30390dfff69bec"
    "453adf21a45ebd52f922bae31adfb2ce" "68db71d6258d3baed1064cb9d26dabe8" "712a425e67ea455e5c0e1a010f2beed2"
    "8aefdd285ef0b319c6c654cebe042c00" "984c5a0871c77b4be3f35e50b5562169" "a7cda6b5093f2ed4432a65fdfc1e3ae8"
    "df257341f217aa7c08d73cc0f0c1ee6d" "fc97d5aec6ecb8150a455e5c0e1a010f2beed2" "fdbf63af94954971ad1fea90533664d8"
    "08c12c2475fff37179438cc4f325f08f" "28c4eae03701eb484686d5b1d4f9c0e8" "368d5e16e8498530a4551a883b4d532d"
    "52a710e8c12b81f03f91b32a49e4b587" "685aacc44cfa18a28d38c4a07cbc1c9a" "7319d40ff352f0f743fb0337253366c3"
    "90c97b7b09f2921ba967bdac17e0633e" "a978a939e073614558b000d814a847a2" "e28867b2c4fd1f02db9d61427d8284ab"
    "3d0669e39a72cbcaffbf11e15e62c4ce" "461f2f063269ccd64880179ae909bd37" "4e014cdb4f6c86fb58fb53f03bf4a51b"
    "75a9e7dc45a1a4923e414cdb4f6c86fb" "8f399605f7eaefc627b4ad657686403d" "919bfd8d9c899b8ccbeec86f25435864"
    "ae33b94972013f4dcaf978c9f2df79c5" "eb0529ed435d48cada1e8ccd524688a4" "0ba735da8cdf5051002edf4e081f4dac"
    "15af1123e6120451c93ddd34eb6f9568" "252418a57d99663ca1e3a88b74e583e7" "77fe6105888e1c96f2cae3eae8394140"
    "987c58e6d4ce229193e7c8664ef66ad9" "a67bcfa3f48e06d8f37206b57fbf85f9" "b91ada8a1edb5fc4351f6943e23f95d1"
    "e56bcefea38cb6bae624bbeedbef6a01" "ed7decac5bd9bf7f527508b4e52d95d2" "7e2deab32ce95d434b42639c74fdba12"
    "9a1a58aaf8002720b19a4cc5cecf28e0" "b99fb15b059585b2e437ff5b3690a676" "fc85adec013f896f21544c549fb35960"
    "059b9b9068b8d0d806a5e134fff970ce"
)
auto_check_permission() {
    if [ "$(id -u)" -eq 0 ]; then
        echo  -e "\033[32m当前为root权限执行\033[0m"
        return 0
    else
        echo -e "\033[32m当前为no root权限执行\033[0m"
        return 1
    fi
}

# Root模式文件替换
root_auto_copy() {
    echo -e "\n\033[34m📂 开始 Root 模式自动处理...\033[0m"
    if [ ! -d "$LOADINGBG_FOLDER" ]; then
        mkdir -p "$LOADINGBG_FOLDER"
        [ $? -eq 0 ] && echo -e "\033[32m✅ 已创建 LoadingBG 目录\033[0m" || { echo -e "\033[31m❌ 创建目录失败\033[0m"; exit 1; }
    fi
    rm -rf "${LOADINGBG_FOLDER}/"*
    cp -f "${OUTPUT_FOLDER}/"* "$LOADINGBG_FOLDER/"
    [ $? -eq 0 ] && echo -e "\033[32m✅ 已完成文件替换（Root模式）\033[0m" || echo -e "\033[31m❌ 文件复制失败\033[0m"
}

# No Root模式提示
no_root_manual_hint() {
    echo -e "\n\033[34m📋 No Root 模式操作提示：\033[0m"
    echo -e "1. 打开MT管理器，授予「访问所有文件」权限"
    echo -e "2. 找到生成文件目录：\033[32m${OUTPUT_FOLDER}\033[0m"
    echo -e "3. 全选文件，复制到目标目录：\033[32m${LOADINGBG_FOLDER}\033[0m"
    echo -e "4. 覆盖原有文件完成替换"
}

# 回车确认
enter_confirm() {
    echo -n "是否确认使用选中文件替换？按回车键继续（直接回车）："
    read -r confirm
    echo
}

# 解析连号（如10-20转为10 11 ... 20）
parse_range() {
    local input="$1"
    local result=()
    for part in $input; do
        if [[ "$part" =~ ^[0-9]+-[0-9]+$ ]]; then
            start=${part%-*}
            end=${part#*-}
            for ((i=start; i<=end; i++)); do result+=("$i"); done
        else
            result+=("$part")
        fi
    done
    echo "${result[@]}"
}

# 精准搜索多文件（完全匹配文件名）
precision_search() {
    local script_dir="$1"
    local output_dir="$2"
    shift 2
    local keywords=($(parse_range "$*"))
    local temp_file="${script_dir}/.tmp_search"
    rm -f "$temp_file"

    for kw in "${keywords[@]}"; do
        find "$script_dir" -maxdepth 10 -type f -name "$kw" ! -path "${output_dir}/*" >> "$temp_file"
    done

    # 去重、过滤空行、排序
    cat "$temp_file" | sort -u | grep -v '^$' > "${temp_file}.filtered"
    local files=($(cat "${temp_file}.filtered"))
    rm -f "$temp_file" "${temp_file}.filtered"

    echo "${files[@]}"
}

# 模糊搜索多文件（文件名包含关键词）
fuzzy_search() {
    local script_dir="$1"
    local output_dir="$2"
    local keyword=$(parse_range "$3")
    local temp_file="${script_dir}/.tmp_search"
    rm -f "$temp_file"

    find "$script_dir" -maxdepth 10 -type f -name "*${keyword}*" ! -path "${output_dir}/*" >> "$temp_file"
    cat "$temp_file" | sort -u | grep -v '^$' > "${temp_file}.filtered"
    local files=($(cat "${temp_file}.filtered"))
    rm -f "$temp_file" "${temp_file}.filtered"

    echo "${files[@]}"
}

# 生成带序号的文件显示（核心修复：序号与文件严格绑定）
show_files_with_number() {
    local files=("$@")
    local display=()
    local idx=1

    echo -e "\n\033[32m✅ 搜索到${#files[@]}个文件，请选择：\033[0m"
    for file in "${files[@]}"; do
        echo "[$idx] $file"
        display+=("$file")
        idx=$((idx+1))
    done

    # 导出全局数组，用于后续序号匹配
    export SELECTABLE_FILES=("${display[@]}")
}

# 选择文件（处理序号输入，支持多序号/连号）
select_files_by_number() {
    local -n result_array=$1
    echo -n "输入选择的序号（支持连号如1-5，空格分隔）："
    read -r input_nums

    # 无输入则默认选第一个
    if [ -z "$input_nums" ]; then
        echo -e "\n\033[33m⚠️  未输入序号，默认选择第一个文件\033[0m"
        result_array+=("${SELECTABLE_FILES[0]}")
        echo -e "\033[32m✅ 选中：${SELECTABLE_FILES[0]}\033[0m"
        return
    fi

    # 解析序号（支持连号）
    local nums=($(parse_range "$input_nums"))
    local total=${#SELECTABLE_FILES[@]}

    for num in "${nums[@]}"; do
        # 校验序号有效性
        if ! [[ "$num" =~ ^[0-9]+$ ]] || [ "$num" -lt 1 ] || [ "$num" -gt "$total" ]; then
            echo -e "\033[33m⚠️  序号$num无效，跳过\033[0m"
            continue
        fi
        # 序号转数组索引（减1）
        local idx=$((num-1))
        result_array+=("${SELECTABLE_FILES[$idx]}")
        echo -e "\033[32m✅ 选中：${SELECTABLE_FILES[$idx]}\033[0m"
    done
}

# 批量处理逻辑
batch_modify() {
    clear
    mkdir -p "$OUTPUT_FOLDER" && rm -rf "${OUTPUT_FOLDER:?}"/*
    echo -e "\033[32m✅ 输出目录已准备：$OUTPUT_FOLDER\033[0m"

    echo -e "\n📌 选择文件数量模式："
    echo -e "[1] 1个文件 | [2] 2个文件 | [3] 3个文件 | [4] 4个文件"
    echo -e "[5] 5个文件 | [6] 6个文件 | [7] 自定义文件（搜索/路径）"
    echo -n "输入数字选择："
    read -r file_count

    if ! [[ "$file_count" =~ ^[1-7]$ ]]; then
        echo -e "\033[31m❌ 选择错误，脚本退出\033[0m"
        exit 1
    fi

    local SOURCE_ARRAY=()
    # 1-6个文件模式（默认取脚本目录下的1、2、3...文件）
    if [ "$file_count" -lt 7 ]; then
        for ((i=1; i<=file_count; i++)); do
            local file="${SCRIPT_DIR}/${i}"
            if [ -f "$file" ]; then
                SOURCE_ARRAY+=("$file")
                echo -e "\033[32m✅ 加载文件：$file\033[0m"
            else
                echo -e "\033[31m❌ 缺少文件：$file，脚本退出\033[0m"
                exit 1
            fi
        done
        enter_confirm
    else
        # 自定义文件模式
        clear
        echo -e "\n📌 选择文件获取方式："
        echo -e "[1] 精准搜索（完全匹配文件名）"
        echo -e "[2] 模糊搜索（文件名包含关键词）"
        echo -e "[3] 指定路径（直接输入文件完整路径）"
        echo -n "输入选项编号："
        read -r get_mode

        case "$get_mode" in
            1)
                echo -n "输入精准搜索关键词（支持连号如10-20，空格分隔）："
                read -r keywords
                local files=($(precision_search "$SCRIPT_DIR" "$OUTPUT_FOLDER" "$keywords"))
                ;;
            2)
                echo -n "输入模糊搜索关键词（支持连号如10-20）："
                read -r keyword
                local files=($(fuzzy_search "$SCRIPT_DIR" "$OUTPUT_FOLDER" "$keyword"))
                ;;
            3)
                echo -n "输入文件完整路径（多个路径用空格分隔）："
                read -r paths
                local files=($paths)
                # 校验路径有效性
                local valid_files=()
                for p in "${files[@]}"; do
                    local real_p=$(readlink -f "$p" 2>/dev/null || echo "$p")
                    [ -f "$real_p" ] && valid_files+=("$real_p") || echo -e "\033[33m⚠️  路径$p无效，跳过\033[0m"
                done
                files=("${valid_files[@]}")
                ;;
            *)
                echo -e "\033[31m❌ 选项错误，脚本退出\033[0m"
                exit 1
                ;;
        esac

        # 校验搜索结果
        if [ ${#files[@]} -eq 0 ]; then
            echo -e "\033[31m❌ 未找到有效文件，脚本退出\033[0m"
            exit 1
        fi

        # 显示文件并选择
        show_files_with_number "${files[@]}"
        select_files_by_number SOURCE_ARRAY

        # 校验选中结果
        if [ ${#SOURCE_ARRAY[@]} -eq 0 ]; then
            echo -e "\033[31m❌ 未选中有效文件，脚本退出\033[0m"
            exit 1
        fi

        enter_confirm
    fi

    # 生成目标文件
    local total_src=${#SOURCE_ARRAY[@]}
    local total_target=${#TARGET_ALL[@]}
    local per_file=$((total_target / total_src))
    local remain=$((total_target % total_src))
    local success=0
    local fail=()

    echo -e "\n🚀 开始生成${total_target}个目标文件..."
    for ((i=0; i<total_src; i++)); do
        local src="${SOURCE_ARRAY[$i]}"
        local count=$per_file
        # 剩余文件分配给最后几个源文件
        [ $i -lt $remain ] && count=$((count+1))

        echo -e "\n处理源文件$((i+1))：$src（生成$count个文件）"
        for ((j=0; j<count; j++)); do
            local target_idx=$((i*per_file + j + (i<remain ? i : remain)))
            [ $target_idx -ge $total_target ] && break
            local target="${OUTPUT_FOLDER}/${TARGET_ALL[$target_idx]}"
            cp -f "$src" "$target" 2>/dev/null
            if [ $? -eq 0 ]; then
                success=$((success+1))
                echo -e "\033[32m✅ 生成：${TARGET_ALL[$target_idx]}\033[0m"
            else
                fail+=("${TARGET_ALL[$target_idx]}")
                echo -e "\033[31m❌ 生成失败：${TARGET_ALL[$target_idx]}\033[0m"
            fi
        done
    done

    # 结果统计
    echo -e "\n🎉 生成完成！"
    echo -e "\033[32m✅ 成功生成：$success 个文件\033[0m"
    [ ${#fail[@]} -gt 0 ] && echo -e "\033[31m❌ 生成失败：${#fail[@]} 个文件（${fail[*]}）\033[0m"

    # 权限处理
    if auto_check_permission; then
        root_auto_copy
    else
        no_root_manual_hint
    fi
}

# 单文件处理逻辑（简化版，仅选一个文件）
single_modify() {
    clear
    mkdir -p "$OUTPUT_FOLDER" && rm -rf "${OUTPUT_FOLDER:?}"/*
    echo -e "\033[32m✅ 输出目录已准备：$OUTPUT_FOLDER\033[0m"

    echo -e "\n📌 选择文件获取方式："
    echo -e "[1] 精准搜索 | [2] 模糊搜索 | [3] 指定路径"
    echo -n "输入选项编号："
    read -r get_mode

    local input_path=""
    case "$get_mode" in
        1)
            echo -n "输入精准搜索关键词："
            read -r kw
            local files=($(precision_search "$SCRIPT_DIR" "$OUTPUT_FOLDER" "$kw"))
            ;;
        2)
            echo -n "输入模糊搜索关键词："
            read -r kw
            local files=($(fuzzy_search "$SCRIPT_DIR" "$OUTPUT_FOLDER" "$kw"))
            ;;
        3)
            echo -n "输入文件完整路径："
            read -r p
            local real_p=$(readlink -f "$p" 2>/dev/null || echo "$p")
            [ -f "$real_p" ] && files=("$real_p") || files=()
            ;;
        *)
            echo -e "\033[31m❌ 选项错误，脚本退出\033[0m"
            exit 1
            ;;
    esac

    if [ ${#files[@]} -eq 0 ]; then
        echo -e "\033[31m❌ 未找到有效文件，脚本退出\033[0m"
        exit 1
    fi

    # 显示并选择单个文件
    show_files_with_number "${files[@]}"
    local selected=()
    select_files_by_number selected
    input_path="${selected[0]}"

    enter_confirm

    # 生成所有目标文件
    local total=${#TARGET_ALL[@]}
    local success=0
    local fail=()

    echo -e "\n🚀 开始生成${total}个目标文件..."
    for target in "${TARGET_ALL[@]}"; do
        local target_path="${OUTPUT_FOLDER}/${target}"
        cp -f "$input_path" "$target_path" 2>/dev/null
        if [ $? -eq 0 ]; then
            success=$((success+1))
        else
            fail+=("$target")
        fi
    done

    # 结果统计
    echo -e "\n🎉 生成完成！"
    echo -e "\033[32m✅ 成功：$success 个 | \033[31m失败：${#fail[@]} 个\033[0m"

    # 权限处理
    if auto_check_permission; then
        root_auto_copy
    else
        no_root_manual_hint
    fi
}

# 主入口
clear
echo "==================== 和平加载图替换工具 ===================="
auto_check_permission
echo -e "\n[1] 批量多文件替换 | [2] 单文件替换"
echo -n "输入选项编号："
read -r main_choice

case "$main_choice" in
    1) batch_modify ;;
    2) single_modify ;;
    *) echo -e "\033[31m❌ 选项错误，脚本退出\033[0m"; exit 1 ;;
esac

echo -e "\n📌 操作完成！按回车键关闭窗口..."
read -r
exit 0
