name: mdBook Publish & Sync

on:
  workflow_run:
    workflows: [mdBook Build & Deploy]
    types: [completed]
    branches: [main]

permissions:
  contents: read
  deployments: write

jobs:
  download-artifact:
    name: Download Build Artifact
    runs-on: ubuntu-latest
    if: github.event.workflow_run.conclusion == 'success'
    outputs:
      artifact-id: ${{ steps.download.outputs.artifact-id }}
    steps:
      - name: Download build artifact
        id: download
        uses: actions/github-script@v7
        with:
          script: |
            const artifacts = await github.rest.actions.listWorkflowRunArtifacts({
              owner: context.repo.owner,
              repo: context.repo.repo,
              run_id: ${{ github.event.workflow_run.id }},
            });

            const artifact = artifacts.data.artifacts.find(a => a.name.startsWith('mdbook-site-'));
            if (!artifact) {
              core.setFailed('No mdBook artifact found');
              return;
            }

            console.log(`✓ Found artifact: ${artifact.name}`);
            console.log(`  Size: ${(artifact.size_in_bytes / 1024 / 1024).toFixed(2)} MB`);
            console.log(`  ID: ${artifact.id}`);
            core.setOutput('artifact-id', artifact.id);

  deploy-custom:
    name: Deploy to Custom Server
    runs-on: ubuntu-latest
    needs: download-artifact
    if: github.event.workflow_run.conclusion == 'success'
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Download artifact
        uses: actions/download-artifact@v4
        with:
          name: mdbook-site-${{ github.event.workflow_run.head_commit.id }}
          path: docs/book/

      - name: Setup SSH key (SSH deployment)
        if: env.DEPLOY_METHOD == 'ssh' || env.DEPLOY_METHOD == 'sftp'
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.DOCS_DEPLOY_KEY }}" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          ssh-keyscan -H "${{ secrets.DOCS_DEPLOY_HOST }}" >> ~/.ssh/known_hosts 2>/dev/null || true
        env:
          DEPLOY_METHOD: ${{ secrets.DOCS_DEPLOY_METHOD }}

      - name: Deploy documentation
        run: bash .scripts/deploy-docs.sh production
        env:
          # Deployment method and settings
          DOCS_DEPLOY_METHOD: ${{ secrets.DOCS_DEPLOY_METHOD }}
          DOCS_DEPLOY_HOST: ${{ secrets.DOCS_DEPLOY_HOST }}
          DOCS_DEPLOY_USER: ${{ secrets.DOCS_DEPLOY_USER }}
          DOCS_DEPLOY_PATH: ${{ secrets.DOCS_DEPLOY_PATH }}

          # HTTP deployment
          DOCS_DEPLOY_ENDPOINT: ${{ secrets.DOCS_DEPLOY_ENDPOINT }}
          DOCS_DEPLOY_TOKEN: ${{ secrets.DOCS_DEPLOY_TOKEN }}

          # AWS S3
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          AWS_DOCS_BUCKET: ${{ secrets.AWS_DOCS_BUCKET }}
          AWS_REGION: ${{ secrets.AWS_REGION }}

          # Google Cloud Storage
          GOOGLE_APPLICATION_CREDENTIALS: ${{ secrets.GCS_CREDENTIALS_FILE }}
          GCS_DOCS_BUCKET: ${{ secrets.GCS_DOCS_BUCKET }}

          # Docker Registry
          DOCKER_REGISTRY: ${{ secrets.DOCKER_REGISTRY }}
          DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
          DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}

      - name: Create deployment record
        uses: actions/github-script@v7
        with:
          script: |
            const deployment = await github.rest.repos.createDeployment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              ref: context.ref,
              environment: 'docs-production',
              description: 'mdBook documentation deployment',
              production_environment: true,
            });

            console.log(`✓ Deployment created: ${deployment.data.id}`);

      - name: Deployment summary
        run: |
          echo "## 📚 Documentation Deployment" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "✅ Successfully deployed to production" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "| Information | Value |" >> $GITHUB_STEP_SUMMARY
          echo "|-------------|-------|" >> $GITHUB_STEP_SUMMARY
          echo "| Environment | Production |" >> $GITHUB_STEP_SUMMARY
          echo "| Commit | ${{ github.event.workflow_run.head_commit.id }} |" >> $GITHUB_STEP_SUMMARY
          echo "| Branch | ${{ github.ref_name }} |" >> $GITHUB_STEP_SUMMARY
          echo "| Deployment Method | ${{ secrets.DOCS_DEPLOY_METHOD }} |" >> $GITHUB_STEP_SUMMARY
          echo "| Timestamp | $(date -u +'%Y-%m-%dT%H:%M:%SZ') |" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY

  notify-deployment:
    name: Notify Deployment Status
    runs-on: ubuntu-latest
    needs: deploy-custom
    if: always()
    steps:
      - name: Deployment notification
        run: |
          if [ "${{ needs.deploy-custom.result }}" == "success" ]; then
            echo "✅ Deployment completed successfully"
            echo "## Deployment Successful" >> $GITHUB_STEP_SUMMARY
          else
            echo "❌ Deployment failed"
            echo "## Deployment Failed" >> $GITHUB_STEP_SUMMARY
          fi

      - name: Send webhook notification
        if: env.NOTIFICATION_WEBHOOK != ''
        run: |
          curl -X POST "${{ secrets.NOTIFICATION_WEBHOOK }}" \
            -H "Content-Type: application/json" \
            -d '{
              "status": "${{ needs.deploy-custom.result }}",
              "environment": "production",
              "commit": "${{ github.event.workflow_run.head_commit.id }}",
              "branch": "${{ github.ref_name }}",
              "timestamp": "'$(date -u +'%Y-%m-%dT%H:%M:%SZ')'",
              "run_url": "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
            }'
        continue-on-error: true
