name: Deploy Documentation

on:
  push:
    branches: [ main, develop ]
    paths: [ 'docs/**' ]
  pull_request:
    branches: [ main ]
    paths: [ 'docs/**' ]
  workflow_dispatch:

permissions:
  contents: read
  pages: write
  id-token: write

concurrency:
  group: "pages"
  cancel-in-progress: false

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'

      - name: Install dependencies
        run: |
          pip install -r docs/requirements.txt

      - name: Generate OpenAPI specs
        run: |
          cd docs
          python scripts/generate_openapi.py

      - name: Build documentation
        run: |
          cd docs
          mkdocs build --strict

      - name: Upload artifact
        uses: actions/upload-pages-artifact@v2
        with:
          path: docs/site

  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    needs: build
    if: github.ref == 'refs/heads/main'
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v2

  # Deploy to staging for develop branch
  deploy-staging:
    runs-on: ubuntu-latest
    needs: build
    if: github.ref == 'refs/heads/develop'
    steps:
      - name: Deploy to Staging
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./docs/site
          destination_dir: staging
          user_name: github-actions[bot]
          user_email: github-actions[bot]@users.noreply.github.com

  # Deploy to production S3
  deploy-production:
    runs-on: ubuntu-latest
    needs: build
    if: github.ref == 'refs/heads/main'
    environment: production
    steps:
      - name: Configure AWS Credentials
        uses: aws-actions/configure-aws-credentials@v2
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: us-east-1

      - name: Deploy to S3
        run: |
          aws s3 sync docs/site/ s3://docs.aitbc.io/ --delete
          aws cloudfront create-invalidation --distribution-id ${{ secrets.CLOUDFRONT_DISTRIBUTION_ID }} --paths "/*"

  # Notify on deployment
  notify:
    runs-on: ubuntu-latest
    needs: [deploy, deploy-production]
    if: always()
    steps:
      - name: Notify Discord
        uses: rjstone/discord-webhook-notify@v1
        with:
          severity: info
          text: "Documentation deployment completed"
          description: |
            Build: ${{ needs.build.result }}
            Deploy: ${{ needs.deploy.result }}
            Production: ${{ needs.deploy-production.result }}
          webhookUrl: ${{ secrets.DISCORD_WEBHOOK }}
