# Before the first run:
# 1. Create a repository secret named DROPLOFT_TOKEN.
# 2. Leave DROPLOFT_DOCUMENT_ID unset so the workflow creates a new document.
# 3. After the first successful publish, copy the emitted document_id into a
#    repository variable named DROPLOFT_DOCUMENT_ID. Future runs will update
#    the same Droploft document instead of creating a new one.

name: Publish HTML to Droploft

on:
  workflow_dispatch:
  push:
    branches:
      - main
    paths:
      - reports/q1-growth.html

jobs:
  drop:
    name: Publish report
    runs-on: ubuntu-latest
    timeout-minutes: 10
    env:
      DROPLOFT_API_URL: https://stage-a.droploft.ai
      DROPLOFT_TOKEN: ${{ secrets.DROPLOFT_TOKEN }}
      DROPLOFT_DOCUMENT_ID: ${{ vars.DROPLOFT_DOCUMENT_ID }}
      REPORT_PATH: reports/q1-growth.html

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: 24.11.0

      - name: Install Droploft CLI beta
        run: |
          curl -fsSLO "${DROPLOFT_API_URL}/droploft-cli-0.4.0.tgz"
          npm install -g ./droploft-cli-0.4.0.tgz

      - name: Publish report
        id: droploft
        shell: bash
        run: |
          set -euo pipefail

          if [ -n "${DROPLOFT_DOCUMENT_ID:-}" ]; then
            droploft update "$DROPLOFT_DOCUMENT_ID" "$REPORT_PATH" --json > droploft.json
          else
            droploft push "$REPORT_PATH" --json > droploft.json
          fi

          node --input-type=module <<'EOF'
          import { appendFileSync, readFileSync } from 'node:fs';

          const result = JSON.parse(readFileSync('droploft.json', 'utf8'));
          const outputs = [
            ['url', result.url ?? ''],
            ['document_id', result.document_id ?? result.id ?? ''],
            ['slug', result.slug ?? ''],
            ['version', result.version ?? ''],
            ['version_url', result.version_url ?? ''],
          ];

          for (const [key, value] of outputs) {
            appendFileSync(process.env.GITHUB_OUTPUT, `${key}=${String(value)}\n`);
          }
          EOF

      - name: Append step summary
        shell: bash
        run: |
          {
            echo "### Droploft publish"
            echo ""
            echo "- URL: ${{ steps.droploft.outputs.url }}"
            echo "- Document ID: \`${{ steps.droploft.outputs.document_id }}\`"
            echo "- Slug: \`${{ steps.droploft.outputs.slug }}\`"
            if [ -n "${{ steps.droploft.outputs.version }}" ]; then
              echo "- Version: \`${{ steps.droploft.outputs.version }}\`"
            fi
            if [ -n "${{ steps.droploft.outputs.version_url }}" ]; then
              echo "- Pinned version URL: ${{ steps.droploft.outputs.version_url }}"
            fi
          } >> "$GITHUB_STEP_SUMMARY"
