name: Build OpenCode CLI

on:
  push:
    branches:
      - main
      - master
    paths:
      - 'opencode/**'
      - '.github/workflows/build-opencode-cli-docker.yml'
  workflow_dispatch:

permissions:
  contents: write
  actions: read

jobs:
  build-cli:
    name: Build OpenCode CLI (x86_64)
    runs-on: ubuntu-24.04
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Bun
        uses: oven-sh/setup-bun@v2
        with:
          bun-version-file: opencode/package.json

      - name: Install dependencies
        run: bun install
        working-directory: opencode
        env:
          HUSKY: 0

      - name: Build CLI
        run: bun run ./packages/opencode/script/build.ts --single
        working-directory: opencode

      - name: Upload CLI artifact
        uses: actions/upload-artifact@v4
        with:
          name: opencode-cli-x86_64
          path: opencode/packages/opencode/dist/opencode-linux-x64
          retention-days: 1

      - name: Create Release
        id: create_release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: opencode-cli-${{ github.sha }}
          release_name: OpenCode CLI ${{ github.sha }}
          draft: false
          prerelease: false

      - name: Upload Release Asset
        uses: actions/upload-release-asset@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          upload_url: ${{ steps.create_release.outputs.upload_url }}
          asset_path: opencode/packages/opencode/dist/opencode-linux-x64/bin/opencode
          asset_name: opencode-linux-x64
          asset_content_type: application/octet-stream

      - name: Cleanup old CLI artifacts
        uses: actions/github-script@v7
        with:
          script: |
            const artifactName = 'opencode-cli-x86_64';
            const { data: artifacts } = await github.rest.actions.listArtifactsForRepo({
              owner: context.repo.owner,
              repo: context.repo.repo,
              name: artifactName,
              per_page: 10
            });
            
            if (artifacts.length > 1) {
              const artifactsToDelete = artifacts.slice(1);
              for (const artifact of artifactsToDelete) {
                await github.rest.actions.deleteArtifact({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  artifact_id: artifact.id
                });
                console.log(`Deleted old artifact: ${artifact.id}`);
              }
            }
