name: "Generate Mod Icons and Convert Images"
description: "Generate WEBP mod icons from skins and convert panel/thumbnail PNGs to WEBPs"

inputs:
  changed_skins_file:
    description: "Path to file with changed skins"
    required: true

runs:
  using: "composite"
  steps:
    - name: Generate Mod Icons (WEBP)
      shell: bash
      run: |
        echo "[Mod Icon Generation Job Started]"

        if [ -z "${{ inputs.changed_skins_file }}" ] || [ ! -s "${{ inputs.changed_skins_file }}" ]; then
          echo "No skins changed. Skipping mod icon generation."
          exit 0
        fi

        mapfile -t skin_dirs < "${{ inputs.changed_skins_file }}"
        [ "${#skin_dirs[@]}" -eq 0 ] && { echo "No skins to process. Exiting."; exit 0; }

        sanitize_filename() {
          echo "$1" | \
            tr -d '\000-\037' | \
            sed -e 's#[\\/:\*\?"<>|]#-#g' | \
            sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
        }

        ICONS_JSON_FILE="${{ github.workspace }}/.gitea/workflows/icons.json"
        group1_icons=$(jq -r '.group1 | join(" ")' "$ICONS_JSON_FILE")
        group2_icons=$(jq -r '.group2 | join(" ")' "$ICONS_JSON_FILE")
        group3_icons=$(jq -r '.group3 | join(" ")' "$ICONS_JSON_FILE")

        BLANK_IMAGE="blank.png"
        magick -size "160x160" xc:none "$BLANK_IMAGE"

        SKIN_COUNT=${#skin_dirs[@]}
        INDEX=1

        for skin_path in "${skin_dirs[@]}"; do
          SKIN_DIR="$DANSER_SKINS_DIR/$skin_path"
          [ ! -d "$SKIN_DIR" ] && { echo "Skipping missing skin directory: $SKIN_DIR"; ((INDEX++)); continue; }

          skin_header="$skin_path"
          ini_file=$(find "$SKIN_DIR" -maxdepth 1 -iname "skin.ini" | head -n1 || true)
          if [ -f "$ini_file" ]; then
            name_line=$(grep -i '^[[:space:]]*Name:' "$ini_file" | head -n1 || true)
            if [ -n "$name_line" ]; then
              val="${name_line#*:}"
              val="$(echo "$val" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
              if [ -n "$val" ]; then
                sanitized="$(sanitize_filename "$val")"
                [ -n "$sanitized" ] && skin_header="$sanitized"
              fi
            fi
          fi

          echo ""
          echo "[$INDEX/$SKIN_COUNT] Skin: $skin_header"

          ICON_FOLDER="$SKIN_DIR"
          OUTPUT_DIR="$REPO_MOD_ICONS_DIR/$skin_path"
          mkdir -p "$OUTPUT_DIR"
          OUTPUT="$OUTPUT_DIR/${skin_header}-mod-icons.webp"

          row_images=()
          row_index=1

          for group_list in "$group1_icons" "$group2_icons" "$group3_icons"; do
            montage_files=()
            for icon in $group_list; do
              file=""
              if [ -f "${ICON_FOLDER}/selection-mod-${icon}@2x.png" ]; then
                file="${ICON_FOLDER}/selection-mod-${icon}@2x.png"
              elif [ -f "${ICON_FOLDER}/selection-mod-${icon}.png" ]; then
                file="${ICON_FOLDER}/selection-mod-${icon}.png"
              elif [ -f "${DEFAULT_SKIN_DIR}/selection-mod-${icon}@2x.png" ]; then
                file="${DEFAULT_SKIN_DIR}/selection-mod-${icon}@2x.png"
              fi

              [ -n "$file" ] && montage_files+=("$file")
            done

            while [ "${#montage_files[@]}" -lt 7 ]; do
              montage_files+=("$BLANK_IMAGE")
            done

            magick montage "${montage_files[@]}" \
              -tile "7x1" -geometry "160x160+10+10" -background none \
              "row_${row_index}.png"
            row_images+=("row_${row_index}.png")
            row_index=$((row_index + 1))
          done

          magick montage "${row_images[@]}" \
            -tile "1x${#row_images[@]}" -geometry "+10+10" -background none \
            "temp_combined.png"

          magick "temp_combined.png" -define webp:lossless=true "$OUTPUT"
          rm temp_combined.png row_*.png

          echo "    ✓ Mod Icons Generated at $OUTPUT"
          INDEX=$((INDEX + 1))
        done

        rm "$BLANK_IMAGE"

        echo ""
        echo "[Mod Icon Generation Finished — processed $SKIN_COUNT skins]"

    - name: Convert PNGs to WEBPs
      shell: bash
      run: |
        echo "[Convert PNG → WEBP Started]"

        if [ -z "${{ inputs.changed_skins_file }}" ] || [ ! -s "${{ inputs.changed_skins_file }}" ]; then
          echo "No skins changed. Skipping conversion."
          exit 0
        fi

        mapfile -t skins < "${{ inputs.changed_skins_file }}"
        [ "${#skins[@]}" -eq 0 ] && { echo "No skins to process. Exiting."; exit 0; }

        convert_pngs_to_webp() {
          local base_dir="$1"
          local skin_path="$2"
          local dir="$base_dir/$skin_path"
          echo " → Processing: $dir"
          [ ! -d "$dir" ] && { echo "    ✖ Directory does not exist: $dir"; return; }
          find "$dir" -type f -iname "*.png" | while read -r png; do
            webp="${png%.png}.webp"
            echo "    ↳ Converting: $png → $webp"
            magick "$png" -define webp:lossless=false -quality 90 "$webp" && rm -f "$png"
          done
        }

        for skin_path in "${skins[@]}"; do
          [ -z "$skin_path" ] && continue
          convert_pngs_to_webp "$REPO_RANKING_PANEL_DIR" "$skin_path"
          convert_pngs_to_webp "$REPO_THUMBNAIL_DIR" "$skin_path"
        done

        echo "[Convert PNG → WEBP Finished]"
