name: Nightly Build

on:
  push:
    branches:
      - nightly
    paths:
      - '**.py'
      - 'Dockerfile'
      - 'requirements.txt'
      - 'web/**'
      - 'data/**'
      - '.gitea/workflows/nightly.yml'
  schedule:
    - cron: '0 2 * * *'
  workflow_dispatch:

jobs:
  build:
    runs-on: server-runner
    steps:
      - name: Checkout
        run: |
          if [ -d .git ]; then
            git fetch --tags origin nightly
            git reset --hard origin/nightly
            git clean -fd
          else
            git clone --branch nightly https://gitea.it-drui.de/viewit/KX-Bridge-Release.git .
          fi

      - name: Install Docker CLI
        run: |
          if ! command -v docker >/dev/null 2>&1; then
            ARCH=$(uname -m)
            if [ "$ARCH" = "x86_64" ]; then
              DARCH="x86_64"
              BARCH="amd64"
            else
              DARCH="aarch64"
              BARCH="arm64"
            fi
            wget -qO- "https://download.docker.com/linux/static/stable/${DARCH}/docker-27.5.1.tgz" \
              | tar xz --strip-components=1 -C /usr/local/bin docker/docker
            chmod +x /usr/local/bin/docker
            mkdir -p /usr/local/lib/docker/cli-plugins
            wget -qO /usr/local/lib/docker/cli-plugins/docker-buildx \
              "https://github.com/docker/buildx/releases/download/v0.23.0/buildx-v0.23.0.linux-${BARCH}"
            chmod +x /usr/local/lib/docker/cli-plugins/docker-buildx
          fi
          docker version --format '{{.Client.Version}}'

      - name: Set up QEMU
        run: |
          docker run --rm --privileged tonistiigi/binfmt:latest --install all

      - name: Set up buildx
        run: |
          docker buildx inspect kxbuilder 2>/dev/null || \
            docker buildx create --name kxbuilder --use
          docker buildx use kxbuilder

      - name: Login to Gitea registry
        run: |
          echo "${{ secrets.REGISTRY_TOKEN }}" | \
            docker login gitea.it-drui.de -u "${{ secrets.REGISTRY_USER }}" --password-stdin

      - name: Compute nightly version
        run: |
          # Letzten Stable-Tag ermitteln (v0.9.27 → minor=27)
          LAST_STABLE=$(git tag --list 'v*' --sort=-version:refname \
            | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+' | { read -r line; echo "$line"; cat >/dev/null; } || true)
          if [ -z "$LAST_STABLE" ]; then
            echo "ERROR: kein Stable-Tag gefunden" >&2; exit 1
          fi
          # Nächste Minor-Version: v0.9.27 → 0.9.28
          MAJOR=$(echo "$LAST_STABLE" | sed 's/^v//' | cut -d. -f1)
          MINOR=$(echo "$LAST_STABLE" | sed 's/^v//' | cut -d. -f2)
          PATCH=$(echo "$LAST_STABLE" | sed 's/^v//' | cut -d. -f3)
          NEXT_PATCH=$((PATCH + 1))
          BASE="${MAJOR}.${MINOR}.${NEXT_PATCH}"
          # Laufende Nummer: Anzahl vorhandener nightly-<BASE>-nightlyX Tags + 1
          COUNT=$(git tag --list "nightly-${BASE}-nightly*" | wc -l | tr -d ' ')
          N=$((COUNT + 1))
          VERSION="${BASE}-nightly${N}"
          echo "VERSION=${VERSION}" > /tmp/nightly_version.env
          echo "BASE=${BASE}" >> /tmp/nightly_version.env
          echo "LAST_STABLE=${LAST_STABLE}" >> /tmp/nightly_version.env
          echo "Computed nightly version: ${VERSION} (after ${LAST_STABLE})"

      - name: Build & push (amd64 + arm64)
        run: |
          . /tmp/nightly_version.env
          # VERSION-Datei im Arbeitsverzeichnis für den Docker-Build setzen (kein Commit)
          echo "$VERSION" > VERSION
          docker buildx build \
            --platform linux/amd64,linux/arm64,linux/arm/v7 \
            --push \
            --provenance=false \
            --no-cache \
            -t "gitea.it-drui.de/viewit/kx-bridge:nightly" \
            -t "gitea.it-drui.de/viewit/kx-bridge:nightly-${VERSION}" \
            .

      - name: Create Gitea Nightly Release
        env:
          GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN }}
        run: |
          . /tmp/nightly_version.env
          TAG="nightly-${VERSION}"

          # Letzten Stable-Tag als Changelog-Basis (nur echte vX.Y.Z-Tags)
          PREV_TAG=$(git tag --list 'v*' --sort=-version:refname \
            | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' \
            | { read -r line; echo "$line"; cat >/dev/null; } || true)
          [ -z "$PREV_TAG" ] && PREV_TAG=$(git rev-list --max-parents=0 HEAD)

          # Changelog: NIGHTLY_CHANGELOG.md hat Vorrang (manuell gepflegt),
          # sonst auto-generiert aus feat/fix-Commits seit letztem Stable-Tag
          BODY_FILE=$(mktemp)
          printf '## KX-Bridge %s — Nightly Build\n\n' "$VERSION" > "$BODY_FILE"
          printf '[experimental] Untested features, for testers only.\n\n' >> "$BODY_FILE"
          if [ -s NIGHTLY_CHANGELOG.md ]; then
            cat NIGHTLY_CHANGELOG.md >> "$BODY_FILE"
          else
            printf '### Changes since `%s`\n\n' "$PREV_TAG" >> "$BODY_FILE"
            git log "${PREV_TAG}..HEAD" --pretty=format:'%s' --no-merges \
              | grep -E '^(feat|fix)[:(]' \
              | grep -Ev '^(feat|fix)\((ci|release|build|workflow)\)' \
              | sed 's/^/- /' \
              >> "$BODY_FILE" || true
            if ! grep -q '^- ' "$BODY_FILE"; then
              printf '- No user-facing changes in this build\n' >> "$BODY_FILE"
            fi
          fi
          printf '\n\n---\n\n### Update Docker image\n\n```bash\ndocker compose pull && docker compose up -d\n```\n\n' >> "$BODY_FILE"
          printf 'Image tag: `gitea.it-drui.de/viewit/kx-bridge:nightly`\n' >> "$BODY_FILE"

          # Tag setzen
          git tag "$TAG"
          git push https://gitea-actions:${GITEA_TOKEN}@gitea.it-drui.de/viewit/KX-Bridge-Release.git "$TAG"

          # curl + jq installieren falls nötig
          if ! command -v curl >/dev/null 2>&1; then
            apk add --no-cache curl 2>/dev/null || \
              { wget -qO /usr/local/bin/curl \
                  "https://github.com/moparisthebest/static-curl/releases/download/v8.6.0/curl-amd64" \
                && chmod +x /usr/local/bin/curl; }
          fi
          if ! command -v jq >/dev/null 2>&1; then
            ARCH=$(uname -m)
            JQ_ARCH="amd64"; [ "$ARCH" = "aarch64" ] && JQ_ARCH="arm64"
            wget -qO /usr/local/bin/jq \
              "https://github.com/jqlang/jq/releases/download/jq-1.7.1/jq-linux-${JQ_ARCH}"
            chmod +x /usr/local/bin/jq
          fi

          # Altes Release löschen falls vorhanden
          curl -s -X DELETE \
            -H "Authorization: token ${GITEA_TOKEN}" \
            "https://gitea.it-drui.de/api/v1/repos/viewit/KX-Bridge-Release/releases/tags/${TAG}" \
            2>/dev/null || true

          # Release erstellen — JSON sicher via jq bauen
          jq -n \
            --arg tag "$TAG" \
            --arg name "KX-Bridge ${VERSION} Nightly" \
            --rawfile body "$BODY_FILE" \
            '{"tag_name":$tag,"name":$name,"body":$body,"draft":false,"prerelease":true}' \
            > /tmp/release_body.json
          curl -s -X POST \
            -H "Authorization: token ${GITEA_TOKEN}" \
            -H "Content-Type: application/json" \
            --data-binary @/tmp/release_body.json \
            "https://gitea.it-drui.de/api/v1/repos/viewit/KX-Bridge-Release/releases"
          rm -f "$BODY_FILE" /tmp/release_body.json
