name: Documentation Automation

on:
  # push:
  #   branches: [main]
  #   paths:
  #     - 'crates/**'
  #     - 'extensions/**'
  workflow_dispatch:
    inputs:
      pr_number:
        description: 'PR number to analyze (gets full PR diff)'
        required: false
        type: string
      trigger_sha:
        description: 'Commit SHA to analyze (ignored if pr_number is set)'
        required: false
        type: string

permissions:
  contents: write
  pull-requests: write

env:
  FACTORY_API_KEY: ${{ secrets.FACTORY_API_KEY }}
  ANALYSIS_MODEL: gemini-3-flash-preview
  WRITING_MODEL: claude-opus-4-5-20251101

jobs:
  docs-automation:
    runs-on: ubuntu-latest
    timeout-minutes: 30

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Droid CLI
        id: install-droid
        run: |
          curl -fsSL https://app.factory.ai/cli | sh
          echo "${HOME}/.local/bin" >> "$GITHUB_PATH"
          echo "DROID_BIN=${HOME}/.local/bin/droid" >> "$GITHUB_ENV"
          # Verify installation
          "${HOME}/.local/bin/droid" --version

      - name: Setup Node.js (for Prettier)
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install Prettier
        run: npm install -g prettier

      - name: Get changed files
        id: changed
        run: |
          if [ -n "${{ inputs.pr_number }}" ]; then
            # Get full PR diff
            echo "Analyzing PR #${{ inputs.pr_number }}"
            echo "source=pr" >> "$GITHUB_OUTPUT"
            echo "ref=${{ inputs.pr_number }}" >> "$GITHUB_OUTPUT"
            gh pr diff "${{ inputs.pr_number }}" --name-only > /tmp/changed_files.txt
          elif [ -n "${{ inputs.trigger_sha }}" ]; then
            # Get single commit diff
            SHA="${{ inputs.trigger_sha }}"
            echo "Analyzing commit $SHA"
            echo "source=commit" >> "$GITHUB_OUTPUT"
            echo "ref=$SHA" >> "$GITHUB_OUTPUT"
            git diff --name-only "${SHA}^" "$SHA" > /tmp/changed_files.txt
          else
            # Default to current commit
            SHA="${{ github.sha }}"
            echo "Analyzing commit $SHA"
            echo "source=commit" >> "$GITHUB_OUTPUT"
            echo "ref=$SHA" >> "$GITHUB_OUTPUT"
            git diff --name-only "${SHA}^" "$SHA" > /tmp/changed_files.txt || git diff --name-only HEAD~1 HEAD > /tmp/changed_files.txt
          fi

          echo "Changed files:"
          cat /tmp/changed_files.txt
        env:
          GH_TOKEN: ${{ github.token }}

      # Filter for docs-relevant files
      - name: "Filter docs-relevant files"
        id: filter
        run: |
          # Patterns for files that could affect documentation
          PATTERNS="crates/.*/src/.*\.rs|assets/settings/.*|assets/keymaps/.*|extensions/.*|docs/.*"
          
          RELEVANT=$(grep -E "$PATTERNS" /tmp/changed_files.txt || true)
          if [ -z "$RELEVANT" ]; then
            echo "No docs-relevant files changed"
            echo "has_relevant=false" >> "$GITHUB_OUTPUT"
          else
            echo "Docs-relevant files found:"
            echo "$RELEVANT"
            echo "has_relevant=true" >> "$GITHUB_OUTPUT"
          fi

      # Combined: Analyze + Plan (using fast model)
      - name: "Analyze & Plan"
        id: analyze
        if: steps.filter.outputs.has_relevant == 'true'
        run: |
          CHANGED_FILES=$(tr '\n' ' ' < /tmp/changed_files.txt)
          
          GUIDELINES='## Documentation Guidelines
          ### Requires Update: New features, changed keybindings, modified settings, deprecated functionality
          ### No Update: Internal refactoring, performance fixes, bug fixes, test/CI changes
          ### Output JSON: {"updates_required": bool, "summary": str, "planned_changes": [{file, section, change_type, description}]}'
          
          "$DROID_BIN" exec \
            -m "$ANALYSIS_MODEL" \
            --auto low \
            "Analyze code changes for documentation impact.
            
            $GUIDELINES
            
            Changed files: $CHANGED_FILES
            
            Output the JSON structure. Be conservative - only flag user-visible changes." \
            > /tmp/analysis.json 2>&1 || true
          
          echo "Analysis complete:"
          cat /tmp/analysis.json
          
          # Check if updates required
          if grep -q '"updates_required":\s*true' /tmp/analysis.json; then
            echo "updates_required=true" >> "$GITHUB_OUTPUT"
          else
            echo "updates_required=false" >> "$GITHUB_OUTPUT"
          fi

      # Combined: Apply + Summarize (using writing model)
      - name: "Apply Documentation Changes"
        id: apply
        if: steps.analyze.outputs.updates_required == 'true'
        run: |
          ANALYSIS=$(cat /tmp/analysis.json)
          
          "$DROID_BIN" exec \
            -m "$WRITING_MODEL" \
            --auto medium \
            "Apply documentation changes from this analysis:
            
            $ANALYSIS
            
            Instructions:
            1. Edit each specified file
            2. Follow mdBook format, use {#kb action::Name} for keybindings
            3. Output summary:
            
            ## Changes Applied
            - [file]: [change]
            
            ## Summary for PR
            [2-3 sentences]" \
            > /tmp/apply-report.md 2>&1 || true
          
          echo "Changes applied:"
          cat /tmp/apply-report.md
          cp /tmp/apply-report.md /tmp/phase6-summary.md

      # Phase 5b: Format with Prettier
      # Format with Prettier (only changed files)
      - name: "Format with Prettier"
        id: format
        if: steps.analyze.outputs.updates_required == 'true'
        run: |
          CHANGED_DOCS=$(git diff --name-only docs/src/ | sed 's|^docs/||' | tr '\n' ' ')
          if [ -n "$CHANGED_DOCS" ]; then
            echo "Formatting: $CHANGED_DOCS"
            cd docs && prettier --write "$CHANGED_DOCS"
          fi

      # Create PR
      - name: "Create PR"
        id: create_pr
        if: steps.analyze.outputs.updates_required == 'true'
        run: |
          # Check if there are actual changes
          if git diff --quiet docs/src/; then
            echo "No documentation changes detected"
            exit 0
          fi

          # Configure git
          git config user.name "factory-droid[bot]"
          git config user.email "138933559+factory-droid[bot]@users.noreply.github.com"

          # Daily batch branch - one branch per day, multiple commits accumulate
          BRANCH_NAME="docs/auto-update-$(date +%Y-%m-%d)"

          # Get source PR info for attribution
          SOURCE_PR_INFO=""
          if [ "${{ steps.changed.outputs.source }}" == "pr" ]; then
            PR_NUM="${{ steps.changed.outputs.ref }}"
            PR_DETAILS=$(gh pr view "$PR_NUM" --json title,author,url 2>/dev/null || echo "{}")
            SOURCE_TITLE=$(echo "$PR_DETAILS" | jq -r '.title // "Unknown"')
            SOURCE_AUTHOR=$(echo "$PR_DETAILS" | jq -r '.author.login // "Unknown"')
            SOURCE_URL=$(echo "$PR_DETAILS" | jq -r '.url // ""')
            SOURCE_PR_INFO="
          ---
          **Source**: [#$PR_NUM]($SOURCE_URL) - $SOURCE_TITLE
          **Author**: @$SOURCE_AUTHOR
          "
          fi

          # Stash local changes from phase 5
          git stash push -m "docs-automation-changes" -- docs/src/

          # Check if branch already exists on remote
          if git ls-remote --exit-code --heads origin "$BRANCH_NAME" > /dev/null 2>&1; then
            echo "Branch $BRANCH_NAME exists, checking out and updating..."
            git fetch origin "$BRANCH_NAME"
            git checkout -B "$BRANCH_NAME" "origin/$BRANCH_NAME"
          else
            echo "Creating new branch $BRANCH_NAME..."
            git checkout -b "$BRANCH_NAME"
          fi

          # Apply stashed changes
          git stash pop || true

          # Stage and commit
          git add docs/src/
          SUMMARY=$(head -50 < /tmp/phase6-summary.md)
          git commit -m "docs: auto-update documentation

          ${SUMMARY}

          Triggered by: ${{ steps.changed.outputs.source }} ${{ steps.changed.outputs.ref }}

          Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>"

          # Push
          git push -u origin "$BRANCH_NAME"

          # Build the PR body section for this update
          PR_BODY_SECTION="## Update from $(date '+%Y-%m-%d %H:%M')
          $SOURCE_PR_INFO
          $(cat /tmp/phase6-summary.md)
          "

          # Check if PR already exists for this branch
          EXISTING_PR=$(gh pr list --head "$BRANCH_NAME" --json number,url,body --jq '.[0]' || echo "")

          if [ -n "$EXISTING_PR" ] && [ "$EXISTING_PR" != "null" ]; then
            PR_NUM=$(echo "$EXISTING_PR" | jq -r '.number')
            PR_URL=$(echo "$EXISTING_PR" | jq -r '.url')
            EXISTING_BODY=$(echo "$EXISTING_PR" | jq -r '.body // ""')
            
            # Append new summary to existing PR body
            NEW_BODY="${EXISTING_BODY}

          ---

          ${PR_BODY_SECTION}"
            
            echo "$NEW_BODY" > /tmp/updated-pr-body.md
            gh pr edit "$PR_NUM" --body-file /tmp/updated-pr-body.md
            
            echo "PR #$PR_NUM updated: $PR_URL"
          else
            # Create new PR
            echo "$PR_BODY_SECTION" > /tmp/new-pr-body.md
            gh pr create \
              --title "docs: automated documentation update ($(date +%Y-%m-%d))" \
              --body-file /tmp/new-pr-body.md \
              --base main || true
            echo "PR created on branch: $BRANCH_NAME"
          fi
        env:
          GH_TOKEN: ${{ github.token }}

      # Summary output
      - name: "Summary"
        if: always()
        run: |
          echo "## Documentation Automation Summary" >> "$GITHUB_STEP_SUMMARY"
          echo "" >> "$GITHUB_STEP_SUMMARY"

          if [ "${{ steps.filter.outputs.has_relevant }}" == "false" ]; then
            echo "No docs-relevant files changed. Skipped analysis." >> "$GITHUB_STEP_SUMMARY"
          elif [ "${{ steps.analyze.outputs.updates_required }}" == "false" ]; then
            echo "No documentation updates required for this change." >> "$GITHUB_STEP_SUMMARY"
          elif [ -f /tmp/phase6-summary.md ]; then
            cat /tmp/phase6-summary.md >> "$GITHUB_STEP_SUMMARY"
          else
            echo "Workflow completed. Check individual step outputs for details." >> "$GITHUB_STEP_SUMMARY"
          fi
