name: Create PRs for pricing updates

on:
  workflow_dispatch: {}
  schedule:
    - cron: 0 0 * * *

permissions:
  contents: write
  pull-requests: write

jobs:
  check-and-create-prs:
    runs-on: amd64-bookworm
    steps:
      - uses: actions/checkout@v5

      - name: Configure git
        run: |
          git config --global user.name "spotpilot-bot"
          git config --global user.email "bot@spotpilot.io"

      - name: Build and check for changes
        run: |
          cargo build -p grid-tariffs-cli
          ./target/debug/grid-tariffs-cli check-all 2>&1 | grep ERROR | xargs -r -I{} echo "::error::{}" || true

      - name: Create PRs for each changed file
        run: |
          # Store the initial state
          base_branch="${{ github.ref_name }}"
          base_sha=$(git rev-parse HEAD)

          git diff --name-only results/*/*.extracted.txt | while IFS= read -r filepath; do
            [ -z "$filepath" ] && continue

            # Extract VAT number and module name from filename
            filename=$(basename "$filepath")
            base="${filename%.extracted.txt}"
            vat="${base%%_*}"
            module="${base#*_}"

            echo "Creating PR for $vat ($module)"

            branch="pricing-update/$vat-$module"

            # Save the changed file content
            temp_file="/tmp/pricing-update-$vat-$module.txt"
            cp "$filepath" "$temp_file"

            # Fetch remote branch if it exists
            git fetch origin "$branch" 2>/dev/null || true

            # Check if remote branch has the same content
            if git show "origin/$branch:$filepath" 2>/dev/null | diff -q - "$temp_file" >/dev/null 2>&1; then
              echo "No changes needed for $vat $module - remote branch already has this content"
              continue
            fi

            # Create or reset branch to base (includes checkout)
            git checkout -B "$branch" "$base_sha"

            # Apply the change
            cp "$temp_file" "$filepath"
            git add "$filepath"

            if ! git diff --cached --quiet; then
              git commit -m "Update pricing for $vat $module"
              git push -f origin "$branch"

              # Create pull request (ignore error if already exists)
              response=$(curl -s -w "\n%{http_code}" -X POST \
                -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
                -H "Content-Type: application/json" \
                -d "{
                  \"title\": \"Pricing update: $vat $module\",
                  \"body\": \"Automated pricing page change detected.\\n\\nPlease review and update the grid operator info in \`src/registry\` if needed.\",
                  \"head\": \"$branch\",
                  \"base\": \"$base_branch\"
                }" \
                "${{ github.api_url }}/repos/${{ github.repository }}/pulls")

              http_code=$(echo "$response" | tail -n1)
              if [ "$http_code" -lt 200 ] || [ "$http_code" -ge 300 ]; then
                echo "$response"
                if [ "$http_code" != "409" ]; then
                  exit 1
                fi
              fi
            fi
          done
