name: Neon Music playlist sync
on:
  push:
    paths:
      - 'state/auth.enc'
      - 'state/config.enc'
      - '.github/workflows/rotation.yml'
      - 'dashboard-template.html'
      - 'dashboard.py'
      - 'cloud.py'
  workflow_dispatch:
    inputs:
      playlist_rules:
        description: "Optional: paste your Neon Music playlist rules JSON"
        required: false
        type: string
  schedule:
    - cron: "17 * * * *"
permissions:
  contents: write
concurrency:
  group: rotation-state
  cancel-in-progress: false
jobs:
  sync:
    if: github.event.repository.private == true
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.repository.default_branch }}
          persist-credentials: true
      - uses: actions/setup-python@v5
        if: hashFiles('state/auth.enc') != ''
        with:
          python-version: "3.12"
      - name: Install encryption dependency
        if: hashFiles('state/auth.enc') != ''
        run: python -m pip install -r requirements.txt
      - name: Apply playlist rules
        if: inputs.playlist_rules != '' && hashFiles('state/auth.enc') != ''
        env:
          PLAYLIST_RULES: ${{ inputs.playlist_rules }}
          ROTATION_STATE_KEY: ${{ secrets.ROTATION_STATE_KEY }}
          PYTHONPATH: ${{ github.workspace }}
        run: |
          rules_file="$(mktemp)"
          trap 'rm -f "$rules_file"' EXIT
          printf '%s' "$PLAYLIST_RULES" > "$rules_file"
          python playlist_rules.py "$rules_file"
      - name: Update playlists
        id: sync
        if: hashFiles('state/auth.enc') != ''
        env:
          ROTATION_STATE_KEY: ${{ secrets.ROTATION_STATE_KEY }}
        run: python cloud.py run
      - name: Awaiting Spotify setup
        if: hashFiles('state/auth.enc') == ''
        run: echo "Spotify setup is required. See README.md."
      - name: Persist encrypted state
        if: always() && steps.sync.outcome != 'skipped'
        run: |
          git config user.name "neonmusic-bot[bot]"
          git config user.email "neonmusic-bot[bot]@users.noreply.github.com"
          if [ -d state ]; then
            git add -A -- state/
            if ! git diff --cached --quiet; then
              git commit -m "Update encrypted Neon Music state"
              git push
            fi
          fi
