# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
# SPDX-License-Identifier: GPL-3.0-or-later
# BRIEF: Auto-build RC release on PR to main, update RC update stream

name: "PR RC Release"

on:
  pull_request:
    types: [opened, synchronize]

env:
  FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
  REGISTRY: code.mokoconsulting.tech
  IMAGE: mokoconsulting/mokogitea

permissions:
  contents: write

jobs:
  rc-release:
    name: Build RC Release
    runs-on: ubuntu-latest
    steps:
      - name: Check target branch
        id: guard
        env:
          BASE_BRANCH: ${{ github.base_ref }}
        run: |
          echo "PR target: ${BASE_BRANCH}"
          if [ "$BASE_BRANCH" != "main" ]; then
            echo "skip=true" >> "$GITHUB_OUTPUT"
            echo "Skipping RC — only for PRs targeting main"
          else
            echo "skip=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Checkout PR branch
        if: steps.guard.outputs.skip != 'true'
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha }}
          fetch-depth: 0

      - name: Determine RC version
        if: steps.guard.outputs.skip != 'true'
        id: version
        env:
          PR_NUMBER: ${{ github.event.pull_request.number }}
        run: |
          BASE_VERSION=$(sed -n 's/.*<version>\(.*\)<\/version>.*/\1/p' updates.xml | head -1)
          [ -z "$BASE_VERSION" ] && BASE_VERSION="04.00.00"
          RC_VERSION="${BASE_VERSION}-rc.${PR_NUMBER}"
          RC_TAG="v1.26.1-moko.${RC_VERSION}"
          echo "version=$RC_VERSION" >> "$GITHUB_OUTPUT"
          echo "tag=$RC_TAG" >> "$GITHUB_OUTPUT"
          echo "RC version: $RC_VERSION (tag: $RC_TAG)"

      - name: Update updates.xml RC channel
        if: steps.guard.outputs.skip != 'true'
        env:
          RC_VERSION: ${{ steps.version.outputs.version }}
          RC_TAG: ${{ steps.version.outputs.tag }}
          PR_URL: ${{ github.event.pull_request.html_url }}
          PR_NUM: ${{ github.event.pull_request.number }}
        run: |
          DOCKER_TAG="${REGISTRY}/${IMAGE}:${RC_TAG}"

          python3 << 'PYEOF'
          import os, re

          rc_version = os.environ["RC_VERSION"]
          rc_tag = os.environ["RC_TAG"]
          pr_url = os.environ["PR_URL"]
          pr_num = os.environ["PR_NUM"]
          docker_tag = os.environ["REGISTRY"] + "/" + os.environ["IMAGE"] + ":" + rc_tag

          entry = f"""  <update>
            <name>MokoGitea</name>
            <description>MokoGitea RC from PR #{pr_num}</description>
            <element>mokogitea</element>
            <type>application</type>
            <version>{rc_version}</version>
            <client>server</client>
            <tags><tag>rc</tag></tags>
            <infourl title="MokoGitea RC">{pr_url}</infourl>
            <downloads>
              <downloadurl type="full" format="docker">{docker_tag}</downloadurl>
            </downloads>
            <sha256></sha256>
            <targetplatform name="mokogitea" version="((1\\.25\\.)|(1\\.26\\.))" />
            <maintainer>Moko Consulting</maintainer>
            <maintainerurl>https://mokoconsulting.tech</maintainerurl>
          </update>"""

          content = open("updates.xml").read()
          # Remove existing RC entry
          content = re.sub(
              r"\s*<update>[\s\S]*?<tag>rc</tag>[\s\S]*?</update>",
              "",
              content,
          )
          # Insert before </updates>
          content = content.replace("</updates>", entry + "\n</updates>")
          open("updates.xml", "w").write(content)
          print(f"Updated updates.xml with RC entry: {rc_version}")
          PYEOF

      - name: Create RC release
        if: steps.guard.outputs.skip != 'true'
        env:
          GITEA_TOKEN: ${{ secrets.MOKOGITEA_TOKEN }}
          RC_TAG: ${{ steps.version.outputs.tag }}
          RC_VERSION: ${{ steps.version.outputs.version }}
          PR_TITLE: ${{ github.event.pull_request.title }}
          PR_URL: ${{ github.event.pull_request.html_url }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
          HEAD_SHA: ${{ github.event.pull_request.head.sha }}
          API_BASE: https://${{ env.REGISTRY }}/api/v1/repos/${{ github.repository }}
        run: |
          # Delete existing RC release/tag if present
          curl -s -X DELETE -H "Authorization: token ${GITEA_TOKEN}" \
            "${API_BASE}/releases/tags/${RC_TAG}" 2>/dev/null || true
          curl -s -X DELETE -H "Authorization: token ${GITEA_TOKEN}" \
            "${API_BASE}/tags/${RC_TAG}" 2>/dev/null || true

          # Create prerelease
          python3 << PYEOF
          import json, os, urllib.request

          api = os.environ["API_BASE"]
          token = os.environ["GITEA_TOKEN"]
          payload = json.dumps({
              "tag_name": os.environ["RC_TAG"],
              "target_commitish": os.environ["HEAD_SHA"],
              "name": f"RC: {os.environ['PR_TITLE']}",
              "body": f"Release candidate from PR #{os.environ['PR_NUMBER']}\n\nPR: {os.environ['PR_URL']}\nDocker: docker pull {os.environ['REGISTRY']}/{os.environ['IMAGE']}:{os.environ['RC_TAG']}",
              "draft": False,
              "prerelease": True,
          }).encode()

          req = urllib.request.Request(
              f"{api}/releases",
              data=payload,
              headers={
                  "Authorization": f"token {token}",
                  "Content-Type": "application/json",
              },
              method="POST",
          )
          with urllib.request.urlopen(req) as resp:
              result = json.loads(resp.read())
              print(f"Created RC release: {result.get('tag_name')}")
          PYEOF

      - name: Commit updates.xml
        if: steps.guard.outputs.skip != 'true'
        env:
          GITEA_TOKEN: ${{ secrets.MOKOGITEA_TOKEN }}
          HEAD_REF: ${{ github.event.pull_request.head.ref }}
          PR_NUM: ${{ github.event.pull_request.number }}
        run: |
          git config user.name "MokoGitea Bot"
          git config user.email "deploy@mokoconsulting.tech"
          git add updates.xml
          if git diff --cached --quiet; then
            echo "No changes to updates.xml"
          else
            git commit -m "chore(ci): update RC stream for PR #${PR_NUM}"
            git push origin "HEAD:${HEAD_REF}" || echo "Push failed"
          fi
