name: Brahe Skill Sync

on:
  schedule:
    - cron: "0 0 1 * *"
  workflow_dispatch:

jobs:
  sync:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write

    steps:
      - uses: actions/checkout@v6
        with:
          ref: main

      - uses: astral-sh/setup-uv@v7

      - name: Set up Python
        uses: actions/setup-python@v6
        with:
          python-version: "3.13.11"

      - name: Sync environment
        run: uv sync

      - name: Generate Brahe skill from upstream
        run: |
          uv run python scripts/generate_brahe_skill.py --output /tmp/brahe-skill-generated

      - name: Compare with committed skill
        id: compare
        run: |
          if [ ! -d ".agents/skills/brahe" ]; then
            echo "has_diff=true" >> "$GITHUB_OUTPUT"
            echo "No committed skill found. Treating as initial generation."
            exit 0
          fi

          if diff -rq .agents/skills/brahe /tmp/brahe-skill-generated > /tmp/diff-summary.txt 2>&1; then
            echo "has_diff=false" >> "$GITHUB_OUTPUT"
          else
            echo "has_diff=true" >> "$GITHUB_OUTPUT"
            {
              echo 'diff_summary<<EOF'
              cat /tmp/diff-summary.txt
              echo 'EOF'
            } >> "$GITHUB_OUTPUT"
          fi

      - name: Create sync PR
        if: steps.compare.outputs.has_diff == 'true'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          DIFF_SUMMARY: ${{ steps.compare.outputs.diff_summary }}
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

          DATE=$(date +%Y-%m-%d)
          BRANCH="sync/brahe-skill-${DATE}"

          git checkout -b "$BRANCH"

          rm -rf .agents/skills/brahe
          cp -r /tmp/brahe-skill-generated .agents/skills/brahe
          git add .agents/skills/brahe

          if git diff --cached --quiet; then
            echo "No changes to commit after copy. Exiting."
            exit 0
          fi

          git commit -m "chore: sync brahe skill with upstream (${DATE})"
          git push origin "$BRANCH"

          EXISTING=$(gh pr list --repo "${{ github.repository }}" --head "$BRANCH" --state open --json number --jq 'length')
          if [ "$EXISTING" -gt 0 ]; then
            echo "An open PR already exists for ${BRANCH}. Skipping creation."
            exit 0
          fi

          # Render PR body with diff summary substituted
          uv run python scripts/render_brahe_skill_pr_body.py

          gh pr create \
            --repo "${{ github.repository }}" \
            --base main \
            --head "$BRANCH" \
            --title "chore: sync brahe skill with upstream (${DATE})" \
            --body-file /tmp/pr-body.md
