name: Community Sync

on:
  workflow_dispatch:
    inputs:
      dry_run:
        description: "Dry run (show what would be removed, don't push)"
        required: false
        default: "false"
        type: boolean
  release:
    types: [published]

permissions:
  contents: read

jobs:
  sync:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Strip commercial content
        run: bash scripts/strip-commercial.sh

      - name: Verify no commercial references remain
        run: |
          failed=0

          if [ -d "agor-pro/" ]; then
            echo "::error::agor-pro/ directory still exists after strip"
            failed=1
          fi

          content=$(find src/lib/commercial/ -type f ! -name '.gitkeep' 2>/dev/null | wc -l)
          if [ "$content" -gt 0 ]; then
            echo "::error::Commercial files remain in src/lib/commercial/"
            failed=1
          fi

          if grep -r "LicenseRef-Commercial" --include="*.ts" --include="*.svelte" \
              --include="*.rs" --include="*.toml" --include="*.json" \
              src/ src-tauri/src/ agor-core/ 2>/dev/null; then
            echo "::error::LicenseRef-Commercial references remain in source"
            failed=1
          fi

          if [ "$failed" -eq 1 ]; then
            exit 1
          fi
          echo "Verification passed: no commercial content remains."

      - name: Show diff summary
        run: |
          echo "=== Files removed or modified ==="
          git status --short
          echo ""
          echo "=== Diff stats ==="
          git diff --stat

      - name: Push to community repo
        if: ${{ github.event.inputs.dry_run != 'true' }}
        env:
          COMMUNITY_PAT: ${{ secrets.COMMUNITY_PAT }}
        run: |
          if [ -z "$COMMUNITY_PAT" ]; then
            echo "::error::COMMUNITY_PAT secret is not set"
            exit 1
          fi

          git config user.name "community-sync[bot]"
          git config user.email "community-sync[bot]@users.noreply.github.com"

          git add -A
          git commit -m "chore: sync community edition from commercial repo

          Stripped commercial content for community release.
          Source: ${{ github.sha }}"

          SYNC_BRANCH="community-sync/${{ github.sha }}"
          git checkout -b "$SYNC_BRANCH"

          git remote add community \
            "https://x-access-token:${COMMUNITY_PAT}@github.com/DexterFromLab/agent-orchestrator.git"

          git push community "$SYNC_BRANCH"

          echo "Pushed branch $SYNC_BRANCH to community repo."
          echo "Create a PR at: https://github.com/DexterFromLab/agent-orchestrator/compare/main...$SYNC_BRANCH"
