# Shotlane visual check: every successful preview deploy (Vercel, Netlify, or anything that reports
# GitHub deployment statuses) is rendered on phone, tablet and desktop, and the screenshots plus any
# problems (sideways scrolling, JavaScript errors, failed requests, broken images) are posted on the PR.
#
# Setup: add the repository secret SHOTLANE_API_KEY (free key: https://shotlane.dev/#signup), copy this
# file to .github/workflows/shotlane-check.yml and edit PAGES. Each page costs 1 credit per device.
# Vercel previews with Deployment Protection: also add the secret VERCEL_AUTOMATION_BYPASS_SECRET
# (Project Settings > Deployment Protection > Protection Bypass for Automation).
name: Shotlane visual check
on: deployment_status
permissions:
  contents: read
  pull-requests: write
jobs:
  check:
    if: github.event.deployment_status.state == 'success' && !contains(github.event.deployment.environment, 'roduction')
    runs-on: ubuntu-latest
    steps:
      - name: Check the preview and comment on the PR
        env:
          PAGES: "/"                       # space-separated paths, e.g. "/ /pricing /blog"
          DEVICES: "iphone,ipad,desktop"   # iphone, iphone_se, pixel, galaxy, ipad, laptop, desktop, desktop_hd
          SHOTLANE_API_KEY: ${{ secrets.SHOTLANE_API_KEY }}
          BYPASS: ${{ secrets.VERCEL_AUTOMATION_BYPASS_SECRET }}
          PREVIEW_URL: ${{ github.event.deployment_status.environment_url || github.event.deployment_status.target_url }}
          SHA: ${{ github.event.deployment.sha }}
          GH_TOKEN: ${{ github.token }}
        run: |
          set -euo pipefail
          head="## Shotlane visual check"
          body="$head"$'\n'"Preview: $PREVIEW_URL ($(cut -c1-7 <<<"$SHA"))"$'\n\n'
          total=0
          for path in $PAGES; do
            req=$(jq -n --arg url "${PREVIEW_URL%/}$path" --arg d "$DEVICES" --arg b "$BYPASS" \
              '{url: $url, devices: ($d | split(",")), keep_days: 30}
               + (if $b != "" then {headers: {"x-vercel-protection-bypass": $b, "x-vercel-set-bypass-cookie": "true"}} else {} end)')
            res=$(curl -sS --max-time 180 -X POST https://shotlane.dev/v1/check -H "Authorization: Bearer $SHOTLANE_API_KEY" \
              -H "Content-Type: application/json" -d "$req")
            total=$((total + $(jq '.issues // 1' <<<"$res")))
            body+=$(jq -r --arg p "$path" '
              "### `\($p)`\n\n" +
              (if .error then "Check failed: \(.error)" else
                "| " + ([.shots[].device] | join(" | ")) + " |\n|" + ([.shots[] | "---"] | join("|")) + "|\n| " +
                ([.shots[] | if .ok then "<a href=\"\(.url)\"><img src=\"\(.url)\" width=\"240\"></a>" else "failed: \(.error)" end] | join(" | ")) + " |\n\n" +
                ([.shots[] | select(.ok) | .device as $d | .issues[] | "- **\($d)**: \(.)"] |
                  if length == 0 then "No problems found." else join("\n") end)
              end)' <<<"$res")$'\n\n'
          done
          body+="<sub>$total problem(s) · screenshots kept 30 days · [Shotlane](https://shotlane.dev/docs#check)</sub>"
          echo "$body" >> "$GITHUB_STEP_SUMMARY"
          pr=$(gh api "repos/$GITHUB_REPOSITORY/commits/$SHA/pulls" --jq '.[0].number // empty')
          [ -z "$pr" ] && { echo "No open PR for $SHA; results are in the job summary."; exit 0; }
          # one comment per PR, updated on every deploy
          id=$(gh api "repos/$GITHUB_REPOSITORY/issues/$pr/comments" --paginate \
            --jq "[.[] | select(.body | startswith(\"$head\"))][0].id // empty" | head -1)
          if [ -n "$id" ]; then
            gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$id" -f body="$body" >/dev/null
          else
            gh api "repos/$GITHUB_REPOSITORY/issues/$pr/comments" -f body="$body" >/dev/null
          fi
