name: Mirror PR to Forgejo

on:
  pull_request:
    types: [opened, synchronize, reopened]

jobs:
  mirror:
    runs-on: ubuntu-latest
    steps:
      - name: Comment on PR
        uses: actions/github-script@v7
        with:
          script: |
            const { data: comments } = await github.rest.issues.listComments({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
            });

            // Don't double-comment
            const botComment = comments.find(c => c.body.includes('mirror-to-forgejo'));
            if (botComment) return;

            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: `<!-- mirror-to-forgejo -->
            👋 Thanks for your contribution! This repo uses [Forgejo](https://git.livingip.xyz/teleo/teleo-codex) as its primary git host. Your PR is being mirrored there for automated review.

            **What happens next:**
            - Your branch is being pushed to our Forgejo instance
            - A corresponding PR will be created for our 3-agent review pipeline
            - Leo (cross-domain), a domain peer, and a self-review agent will evaluate your changes
            - If approved, it merges on Forgejo and syncs back here automatically

            You don't need to do anything — we'll update this PR with the review results.

            *Teleo eval pipeline — [git.livingip.xyz](https://git.livingip.xyz/teleo/teleo-codex)*`
            });

      - name: Checkout PR branch
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.ref }}
          fetch-depth: 0

      - name: Mirror branch to Forgejo
        env:
          FORGEJO_TOKEN: ${{ secrets.FORGEJO_MIRROR_TOKEN }}
        run: |
          BRANCH="${{ github.event.pull_request.head.ref }}"

          # Add Forgejo remote
          git remote add forgejo "https://github-mirror:${FORGEJO_TOKEN}@git.livingip.xyz/teleo/teleo-codex.git"

          # Push the branch
          git push forgejo "HEAD:refs/heads/${BRANCH}" --force

          echo "Branch ${BRANCH} pushed to Forgejo"

      - name: Create PR on Forgejo
        env:
          FORGEJO_TOKEN: ${{ secrets.FORGEJO_MIRROR_TOKEN }}
        run: |
          BRANCH="${{ github.event.pull_request.head.ref }}"
          TITLE="${{ github.event.pull_request.title }}"
          BODY="${{ github.event.pull_request.body }}"
          GH_PR="${{ github.event.pull_request.number }}"
          GH_AUTHOR="${{ github.event.pull_request.user.login }}"

          # Check if PR already exists for this branch
          EXISTING=$(curl -s -H "Authorization: token ${FORGEJO_TOKEN}" \
            "https://git.livingip.xyz/api/v1/repos/teleo/teleo-codex/pulls?state=open" \
            | jq -r ".[] | select(.head.ref == \"${BRANCH}\") | .number")

          if [ -n "$EXISTING" ]; then
            echo "PR already exists on Forgejo: #${EXISTING}"
            exit 0
          fi

          # Create PR on Forgejo
          PR_BODY="Mirrored from GitHub PR #${GH_PR} by @${GH_AUTHOR}

          ${BODY}

          ---
          *Mirrored automatically from [GitHub PR #${GH_PR}](https://github.com/living-ip/teleo-codex/pull/${GH_PR})*"

          RESPONSE=$(curl -s -X POST \
            -H "Authorization: token ${FORGEJO_TOKEN}" \
            -H "Content-Type: application/json" \
            -d "$(jq -n --arg title "$TITLE" --arg body "$PR_BODY" --arg head "$BRANCH" \
              '{title: $title, body: $body, head: $head, base: "main"}')" \
            "https://git.livingip.xyz/api/v1/repos/teleo/teleo-codex/pulls")

          FORGEJO_PR=$(echo "$RESPONSE" | jq -r '.number // empty')

          if [ -n "$FORGEJO_PR" ]; then
            echo "Created Forgejo PR #${FORGEJO_PR}"
          else
            echo "Failed to create Forgejo PR:"
            echo "$RESPONSE"
            exit 1
          fi
