name: 'Check App Accessibility'
description: 'Parse logs and check if the app is running'
inputs:
  log-file:
    description: 'The path to the log file containing the serve output'
    required: true
  api-key:
    description: 'The API key for accessing the app'
    required: false

runs:
  using: "composite"
  steps:
    - name: Parse logs and check if app is running
      id: check-app
      shell: bash
      run: |

        echo "Serve output:"
        cat ${{ inputs.log-file }}
        APP_URL=$(grep -oP 'You can access it here: \K.+' ${{ inputs.log-file }} | head -n 1)
        echo "Extracted app URL: $APP_URL"
        if [ -z "$APP_URL" ]; then
            echo "Error: Failed to extract app URL from logs."
            exit 1
        fi
        APP_URL="${APP_URL%/}/openapi.json"

        echo "Checking if $APP_URL is accessible"
        retries=6
        for i in $(seq 1 $retries); do
            status_code=$(curl --max-time 60 --write-out %{http_code} --silent --output /dev/null --verbose $APP_URL)
            echo "Attempt $i: Status code: $status_code"
            if [ "$status_code" -eq 200 ]; then
                echo "$APP_URL is accessible without API key"
                exit 0
            elif [ "$status_code" -eq 401 ]; then
                if [ -z "${{ inputs.api-key }}" ]; then
                    echo "Error: $APP_URL is not accessible without API key"
                    sleep 10 # Wait before retrying
                fi
                status_code=$( \
                  curl --max-time 60 --write-out %{http_code} --silent --output /dev/null --verbose \
                  -H "Authorization: ApiKey ${{ inputs.api-key }}" \
                  $APP_URL)
                echo "Attempt $i: Status code: $status_code"
                if [ "$status_code" -eq 200 ]; then
                    echo "$APP_URL is accessible with API key"
                    exit 0
                else
                    echo "Attempt $i failed: $APP_URL is not accessible"
                    sleep 10 # Wait before retrying
                fi
            else
                echo "Attempt $i failed: $APP_URL is not accessible"
                sleep 10 # Wait before retrying
            fi
        done

        echo "Error: $APP_URL is not accessible after $retries attempts"
        exit 1
