name: Publish Elixir SDK

on:
  schedule:
    # Run daily at 06:00 UTC
    - cron: '0 6 * * *'
  push:
    branches:
      - main
    paths:
      - 'apps/elixir-sdk/**'
  workflow_dispatch:

defaults:
  run:
    working-directory: ./apps/elixir-sdk

jobs:
  regenerate:
    if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
    runs-on: blacksmith-2vcpu-ubuntu-2404

    steps:
      - name: Checkout repository
        uses: actions/checkout@v5

      - name: Set up Elixir
        uses: erlef/setup-beam@ee09b1e59bb240681c382eb1f0abc6a04af72764 # v1
        with:
          elixir-version: '1.17'
          otp-version: '27'

      - name: Install dependencies
        run: mix deps.get

      - name: Regenerate from OpenAPI spec
        run: mix run generate.exs

      - name: Check for changes
        id: check_changes
        run: |
          if git diff --quiet HEAD -- . && [ -z "$(git ls-files --others --exclude-standard .)" ]; then
            echo "changed=false" >> "$GITHUB_OUTPUT"
          else
            echo "changed=true" >> "$GITHUB_OUTPUT"
          fi

      - name: Create PR with regenerated code
        if: steps.check_changes.outputs.changed == 'true'
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          cd "$GITHUB_WORKSPACE"

          VERSION=$(grep '@version' apps/elixir-sdk/mix.exs | head -1 | sed 's/.*"\(.*\)".*/\1/')
          if [ -z "$VERSION" ]; then
            echo "::error::Could not parse version from mix.exs"
            exit 1
          fi
          BRANCH="chore/elixir-sdk-regen-v${VERSION}"

          # Check if a PR already exists for this version.
          # If gh fails, abort rather than risk deleting a live PR branch.
          if ! PR_JSON=$(gh pr list --head "$BRANCH" --state open --json number 2>&1); then
            echo "::error::Failed to check for existing PRs: $PR_JSON"
            exit 1
          fi
          EXISTING_PR=$(echo "$PR_JSON" | jq -r '.[0].number // empty')
          if [ -n "$EXISTING_PR" ]; then
            echo "PR #${EXISTING_PR} already exists for ${BRANCH} — skipping."
            exit 0
          fi

          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"

          # Delete stale remote branch if it exists (no open PR at this point)
          git push origin --delete "$BRANCH" 2>/dev/null || true

          git checkout -b "$BRANCH"
          git add apps/elixir-sdk/
          git commit -m "chore(elixir-sdk): regenerate from OpenAPI spec (v${VERSION})"
          git push -u origin "$BRANCH"

          PR_BODY=$(cat <<EOF
          Auto-generated PR to update the Elixir SDK from the latest OpenAPI spec.

          ## Changes
          - Regenerated \`lib/firecrawl.ex\` from the v2 OpenAPI spec
          - Version bumped to \`${VERSION}\`

          This PR was created automatically by the \`publish-elixir-sdk\` workflow.
          EOF
          )

          gh pr create \
            --title "chore(elixir-sdk): regenerate from OpenAPI spec (v${VERSION})" \
            --body "$PR_BODY" \
            --head "$BRANCH" \
            --base main

  publish:
    if: github.event_name == 'push'
    runs-on: blacksmith-2vcpu-ubuntu-2404

    steps:
      - name: Checkout repository
        uses: actions/checkout@v5

      - name: Set up Elixir
        uses: erlef/setup-beam@ee09b1e59bb240681c382eb1f0abc6a04af72764 # v1
        with:
          elixir-version: '1.17'
          otp-version: '27'

      - name: Install dependencies
        run: mix deps.get

      - name: Check if version needs publishing
        id: version_info
        run: |
          LOCAL_VERSION=$(grep '@version' mix.exs | head -1 | sed 's/.*"\(.*\)".*/\1/')
          if [ -z "$LOCAL_VERSION" ]; then
            echo "::error::Could not parse local version from mix.exs"
            exit 1
          fi
          echo "local_version=$LOCAL_VERSION" >> "$GITHUB_OUTPUT"

          # Check published version on hex.pm
          HTTP_STATUS=$(curl -s -o /tmp/hex_response.json -w "%{http_code}" "https://hex.pm/api/packages/firecrawl")
          if [ "$HTTP_STATUS" = "200" ]; then
            PUBLISHED_VERSION=$(python3 -c "import sys,json; releases=json.load(open('/tmp/hex_response.json'))['releases']; print(releases[0]['version'] if releases else '0.0.0')")
          else
            PUBLISHED_VERSION="0.0.0"
          fi
          echo "published_version=$PUBLISHED_VERSION" >> "$GITHUB_OUTPUT"

          # Compare versions using simple tuple comparison
          python3 -c "
          local = tuple(map(int, '$LOCAL_VERSION'.split('.')))
          pub = tuple(map(int, '$PUBLISHED_VERSION'.split('.')))
          print('should_publish=true' if local > pub else 'should_publish=false')
          " >> "$GITHUB_OUTPUT"

      - name: Publish to hex.pm
        if: steps.version_info.outputs.should_publish == 'true'
        env:
          HEX_API_KEY: ${{ secrets.HEX_API_KEY }}
        run: |
          mix hex.publish --yes
