name: 'Resize Images'
description: 'Resize images in CI using Agent Media Tools'
inputs:
  pattern:
    description: 'Glob pattern to search for images (e.g., "images/**/*")'
    required: true
    default: '**/*'
  width:
    description: 'Target width in pixels'
    required: false
    default: '800'
  format:
    description: 'Output format (webp, jpeg, png)'
    required: false
    default: 'webp'
  api-key:
    description: 'Agent Media Tools API key'
    required: true
runs:
  using: 'composite'
  steps:
    - env:
        AMT_API_KEY: ${{ inputs.api-key }}
        INPUT_PATTERN: ${{ inputs.pattern }}
        TARGET_WIDTH: ${{ inputs.width }}
        OUTPUT_FORMAT: ${{ inputs.format }}
      run: |
        [[ "$TARGET_WIDTH" =~ ^[0-9]+$ ]] || { echo "width must be numeric" >&2; exit 2; }
        [[ "$OUTPUT_FORMAT" =~ ^(webp|jpeg|png)$ ]] || { echo "unsupported format" >&2; exit 2; }
        mapfile -d '' images < <(python3 -c 'import glob, os, sys; [os.write(1, os.fsencode(p) + b"\0") for p in glob.glob(sys.argv[1], recursive=True) if os.path.isfile(p) and os.path.splitext(p)[1].lower() in {".jpg", ".jpeg", ".png"}]' "$INPUT_PATTERN")
        ((${#images[@]})) || { echo "No files matched: $INPUT_PATTERN" >&2; exit 1; }
        for img in "${images[@]}"; do
          echo "Resizing $img → ${TARGET_WIDTH}px $OUTPUT_FORMAT"
          curl --fail-with-body --show-error --silent --retry 2 -X POST "https://agentmediatools.com/api/resize-image" \
            -H "Authorization: Bearer $AMT_API_KEY" \
            -F "image=@$img" \
            -F "width=$TARGET_WIDTH" \
            -F "format=$OUTPUT_FORMAT" \
            -o "${img%.*}.$OUTPUT_FORMAT"
        done
        echo "✅ Done — resized to ${TARGET_WIDTH}px $OUTPUT_FORMAT"
      shell: bash
