name: Release

on:
  push:
    tags: ["v*"]

permissions:
  contents: write

jobs:
  # ── Prepare version ─────────────────────────────────────────
  prepare:
    runs-on: [self-hosted, Linux]
    outputs:
      version: ${{ steps.ver.outputs.version }}
    steps:
      - id: ver
        run: echo "version=${GITHUB_REF_NAME#v}" >> $GITHUB_OUTPUT
    env:
      PATH: /home/ivan/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

  # ── Lint ──────────────────────────────────────────────────────
  check:
    uses: ./.github/workflows/check.yml

  # ── Build all platforms ──────────────────────────────────────
  build-linux:
    needs: [check, prepare]
    uses: ./.github/workflows/build-linux.yml
    with:
      version: ${{ needs.prepare.outputs.version }}

  build-windows:
    needs: [check, prepare]
    uses: ./.github/workflows/build-windows.yml
    with:
      version: ${{ needs.prepare.outputs.version }}

  build-macos:
    needs: [check, prepare]
    uses: ./.github/workflows/build-macos.yml
    with:
      version: ${{ needs.prepare.outputs.version }}

  # ── Publish to crates.io ──────────────────────────────────────
  publish:
    name: Publish to crates.io
    needs: [check, prepare]
    runs-on: [self-hosted, Linux]

    env:
      PATH: /home/ivan/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

    steps:
      - uses: actions/checkout@v4

      - name: Set version
        run: sed -i "s/^version = .*/version = \"${{ needs.prepare.outputs.version }}\"/" Cargo.toml

      - name: Publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        run: cargo publish --allow-dirty

  # ── Create GitHub Release ────────────────────────────────────
  release:
    name: Create Release
    needs: [build-linux, build-windows, build-macos, publish]
    runs-on: [self-hosted, Linux]

    env:
      PATH: /home/ivan/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

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

      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: release-assets
          merge-multiple: true

      - name: Generate checksums
        run: |
          cd release-assets
          sha256sum * > checksums-sha256.txt
          cat checksums-sha256.txt

      - name: Generate changelog
        id: changelog
        run: |
          PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
          if [ -n "$PREV_TAG" ]; then
            echo "Changes since $PREV_TAG:"
            CHANGELOG=$(git log "$PREV_TAG"..HEAD --pretty=format:"- %s" --no-merges)
          else
            CHANGELOG=$(git log --pretty=format:"- %s" --no-merges -20)
          fi
          # Write to file for multiline support
          echo "$CHANGELOG" > /tmp/changelog.txt
          echo "prev_tag=$PREV_TAG" >> $GITHUB_OUTPUT

      - name: Prepare release body
        run: |
          VERSION="${{ github.ref_name }}"
          CHANGELOG=$(cat /tmp/changelog.txt)
          CHECKSUMS=$(cat release-assets/checksums-sha256.txt)
          cat > /tmp/release-body.md <<EOF
          ## telegram-bot-mcp ${VERSION}

          Telegram Bot API MCP server & CLI. Full coverage of 130 Bot API methods.

          ### Install
          \`\`\`bash
          cargo install telegram-bot-mcp
          \`\`\`
          Or download a binary below.

          ### Binaries
          | Platform | File |
          |---|---|
          | Linux x86_64 | \`telegram-bot-mcp-${VERSION}-linux-x86_64\` |
          | Windows x86_64 | \`telegram-bot-mcp-${VERSION}-windows-x86_64.exe\` |
          | macOS x86_64 | \`telegram-bot-mcp-${VERSION}-macos-x86_64\` |

          ### Changes
          ${CHANGELOG}

          ### Checksums (SHA-256)
          \`\`\`
          ${CHECKSUMS}
          \`\`\`
          EOF

      - name: Create GitHub Release
        env:
          GITHUB_TOKEN: ${{ github.token }}
        run: |
          VERSION="${{ github.ref_name }}"
          REPO="${{ github.repository }}"

          # Create release
          RELEASE_ID=$(curl -s -X POST \
            -H "Authorization: token $GITHUB_TOKEN" \
            -H "Accept: application/vnd.github+json" \
            "https://api.github.com/repos/$REPO/releases" \
            -d "$(jq -n --arg tag "$VERSION" --arg name "$VERSION" --rawfile body /tmp/release-body.md '{tag_name: $tag, name: $name, body: $body, draft: false}')" \
            | jq -r '.id')

          echo "Release ID: $RELEASE_ID"

          # Upload assets
          for FILE in release-assets/*; do
            FILENAME=$(basename "$FILE")
            echo "Uploading $FILENAME..."
            curl -s -X POST \
              -H "Authorization: token $GITHUB_TOKEN" \
              -H "Content-Type: application/octet-stream" \
              "https://uploads.github.com/repos/$REPO/releases/$RELEASE_ID/assets?name=$FILENAME" \
              --data-binary "@$FILE"
          done

          echo "Release created: https://github.com/$REPO/releases/tag/$VERSION"
