name: Build and Deploy Documentation

on:
  push:
    branches:
      - main
    paths:
      - 'docs/**'
      - '.github/workflows/docs.yml'
    tags:
      - 'v*'
  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@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
        with:
          fetch-depth: 0  # Needed for git info

      - name: Setup Hugo
        uses: peaceiris/actions-hugo@16361eb4acea8698b220b76c0d4e84e1fd22c61d # v2
        with:
          hugo-version: 'latest'
          extended: true

      - name: Setup Go
        uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5
        with:
          go-version: '1.21'

      - name: Setup Node.js
        uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
        with:
          node-version: '20'
          cache: 'npm'
          cache-dependency-path: docs/package-lock.json

      - name: Install Go dependencies
        working-directory: docs
        run: |
          go mod download
          go mod tidy

      - name: Install npm dependencies
        working-directory: docs
        run: |
          npm ci

      - name: Fetch metadata
        working-directory: docs
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          # CRATES_IO_TOKEN not needed for public API access, but kept for future use
          CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
        run: |
          mkdir -p scripts
          chmod +x scripts/fetch-metadata.sh || true
          ./scripts/fetch-metadata.sh static/metadata.json || echo "Metadata fetch failed, continuing..."

      - name: Build Hugo site
        working-directory: docs
        run: |
          hugo --minify --baseURL "https://flux9s.ca/"

      - name: Copy metadata.json to public
        working-directory: docs
        run: |
          if [ -f static/metadata.json ]; then
            cp static/metadata.json public/metadata.json
          else
            echo '{"crates_downloads": 0, "github_stars": 0, "github_releases": 0, "last_updated": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'"}' > public/metadata.json
          fi

      - name: Setup Pages
        uses: actions/configure-pages@1f0c5cde4bc74cd7e1254d0cb4de8d49e9068c7d # v4

      - name: Upload artifact
        uses: actions/upload-pages-artifact@56afc609e74202658d3ffba0e8f6dda462b719fa # v3
        with:
          path: docs/public

  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4
