#!/bin/bash

MODE=""
TAGS=()

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case "$1" in
        --native)
            MODE="native"
            shift
            ;;
        --amber-ce-*)
            MODE="amber"
            TAGS+=("${1#--}")  # Store the clean tag (amber-ce-xxx)
            shift
            ;;
        --auto)
            MODE="auto"
            shift
            ;;
        *)
            # Assume it's a directory
            if [ -z "$SEARCH_DIRS" ]; then
                SEARCH_DIRS=("$1")
            else
                SEARCH_DIRS+=("$1")
            fi
            shift
            ;;
    esac
done

if [ -z "$MODE" ]; then
    echo "使用方法: $0 [--native | --amber-ce-xxx | --auto] <目录1> [目录2 ...]"
    exit 1
fi

if [ "${#SEARCH_DIRS[@]}" -eq 0 ]; then
    echo "错误: 必须提供至少一个目录"
    exit 1
fi

for dir in "${SEARCH_DIRS[@]}"; do
    if [ ! -d "$dir" ]; then
        echo "错误: 目录 '$dir' 不存在"
        exit 1
    fi
done

process_file() {
    local file="$1"
    local temp_file
    temp_file=$(mktemp)
    
    # Process the file based on mode
    case "$MODE" in
        "native")
            jq --indent 4 '
            def process_tags(tags):
                if type == "string" then
                    (split(";") | 
                    map(select(. != "")) | 
                    map(select(. | startswith("amber-ce-") | not)) |
                    if index("native") == null then . + ["native"] else . end) | join(";")
                elif type == "array" then
                    (map(select(. | startswith("amber-ce-") | not)) |
                    if index("native") == null then . + ["native"] else . end)
                else
                    ["native"]
                end;
            
            if has("Tags") then
                .Tags |= process_tags(.)
            else
                . + {Tags: "native"}
            end
            ' "$file" > "$temp_file"
            ;;
        "amber")
            # Convert tags to JSON array and escape for jq
            local tags_json
            tags_json=$(printf '%s\n' "${TAGS[@]}" | jq -R . | jq -s .)
            
            jq --indent 4 --argjson tags "$tags_json" '
            def process_tags(existing):
                $tags as $new_tags |
                if type == "string" then
                    (split(";") | 
                    map(select(. != "")) | 
                    map(select(. == "native" | not)) |
                    (if length == 0 then $new_tags else . + $new_tags end | unique)) | join(";")
                elif type == "array" then
                    (map(select(. == "native" | not)) + $new_tags) | unique
                else
                    $new_tags
                end;
            
            if has("Tags") then
                .Tags |= process_tags(.)
            else
                . + {Tags: ($tags | join(";"))}
            end
            ' "$file" > "$temp_file"
            ;;
        "auto")
            jq --indent 4 '
            def process_tags(tags):
                if type == "string" then
                    (split(";") | 
                    map(select(. != "")) | 
                    map(select(. == "native" | not)) |
                    map(select(. | startswith("amber-ce-") | not))) | join(";")
                elif type == "array" then
                    (map(select(. == "native" | not)) |
                    map(select(. | startswith("amber-ce-") | not)))
                else
                    []
                end;
            
            if has("Tags") then
                .Tags |= process_tags(.)
            else
                . 
            end
            ' "$file" > "$temp_file"
            ;;
    esac

    if [ ! -s "$temp_file" ]; then
        echo "[错误: 处理失败] $file"
        rm -f "$temp_file"
        return 1
    fi

    if ! cmp -s "$file" "$temp_file"; then
        # Ensure the file ends with a newline
        (cat "$temp_file"; echo) | sed '${/^$/d}' > "${temp_file}.tmp"
        mv "${temp_file}.tmp" "$file"
        echo "[修改成功] $file"
    else
        echo "[跳过未变更] $file"
    fi
    rm -f "$temp_file"
}

for dir in "${SEARCH_DIRS[@]}"; do
    find "$dir" -type f -name "app.json" -print0 | while IFS= read -r -d $'\0' file; do
        process_file "$file" || continue
    done
done

echo "处理完成"
