name: Stable Release

on:
  pull_request:
    branches: [master]
    types: [closed]

  workflow_dispatch:
    inputs:
      ref:
        description: "Git ref to build (branch/tag/SHA). Default: master"
        required: false
        default: "master"
      allow_existing_release:
        description: "If true, update assets even when the stable tag already exists"
        required: false
        type: boolean
        default: true

permissions:
  contents: write

env:
  PRODUCT_NAME: Jellyfin2Samsung
  PROJECT_DIR: Jellyfin2Samsung-CrossOS
  CONFIGURATION: Release

jobs:
# ======================================================
# STABLE RELEASE + WINDOWS + LINUX (tar.gz + deb)
# ======================================================
  stable-release:
    if: |
      (github.event_name == 'pull_request' &&
       github.event.pull_request.merged == true &&
       github.event.pull_request.base.ref == 'master' &&
       github.event.pull_request.head.ref == 'beta') ||
      (github.event_name == 'workflow_dispatch')
    runs-on: ubuntu-latest

    outputs:
      VERSION: ${{ steps.version.outputs.VERSION }}
      VERSION_TAG: ${{ steps.version.outputs.VERSION_TAG }}

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.ref }}

      # ---------------- VERSION (NO -beta allowed) ----------------
      - name: Validate AppVersion (must be stable)
        id: version
        shell: bash
        run: |
          FILE="${PROJECT_DIR}/Helpers/AppSettings.cs"

          VERSION_LINE=$(grep 'AppVersion' "$FILE" || true)

          if echo "$VERSION_LINE" | grep -q '\-beta"'; then
            echo "❌ AppVersion still contains '-beta'"
            echo "   Stable releases must use a clean version like v2.0.0.1"
            exit 1
          fi

          VERSION=$(echo "$VERSION_LINE" | grep -oE 'v[0-9]+(\.[0-9]+){1,3}')

          if [ -z "$VERSION" ]; then
            echo "❌ Failed to extract stable version"
            exit 1
          fi

          echo "VERSION=${VERSION#v}" >> "$GITHUB_ENV"
          echo "VERSION_TAG=${VERSION}" >> "$GITHUB_ENV"

          echo "VERSION=${VERSION#v}" >> "$GITHUB_OUTPUT"
          echo "VERSION_TAG=${VERSION}" >> "$GITHUB_OUTPUT"

      # --------------------------------------------------
      # Guard (log-only): create or update assets
      # --------------------------------------------------
      - name: Stable release exists? (allow updating assets)
        shell: bash
        run: |
          if git tag --list | grep -qx "$VERSION_TAG"; then
            echo "ℹ️ Stable release $VERSION_TAG already exists — will update assets"
          else
            echo "ℹ️ Stable release $VERSION_TAG does not exist — will create it"
          fi

      # --------------------------------------------------
      # Optional: in manual runs, allow user to DISABLE updating an existing release
      # --------------------------------------------------
      - name: Stop if release exists and manual updating is disabled
        if: github.event_name == 'workflow_dispatch' && inputs.allow_existing_release == false
        shell: bash
        run: |
          if git tag --list | grep -qx "$VERSION_TAG"; then
            echo "ℹ️ Release $VERSION_TAG already exists and allow_existing_release=false — exiting"
            exit 0
          fi

      # ---------------- CHANGELOG (from last stable tag) ----------------
      - name: Generate changelog
        shell: bash
        run: |
          LAST_STABLE=$(git tag \
            | grep -E '^v[0-9]+(\.[0-9]+){1,3}$' \
            | sort -V \
            | tail -n 1)

          if [ -z "$LAST_STABLE" ]; then
            RANGE="HEAD"
          else
            RANGE="$LAST_STABLE..HEAD"
          fi

          {
            echo "## ✅ What's New & Improved"
            git log $RANGE --pretty=format:"- %s"
          } > CHANGELOG.md

      # ---------------- RELEASE NOTES ----------------
      - name: Prepare release notes
        shell: bash
        run: |
          DATE=$(date +'%Y-%m-%d')
          {
            echo "## 📦 [${VERSION_TAG}] – ${DATE}"
            echo ""
            cat CHANGELOG.md
            echo ""
            echo ""
            echo "| Platform | Status | Notes |"
            echo "|----------|--------|-------|"
            echo "| 🍎 macOS (.app + dmg) | ✅ Stable | ARM64 + Intel |"
            echo "| 🍎 macOS (CLI) | ✅ Stable | Per-arch tar.gz |"
            echo "| 🐧 Linux | ✅ Stable | tar.gz / .deb |"
            echo "| 🪟 Windows | ✅ Stable | CI-built |"
            echo ""
            echo "---"
            echo ""
            echo "### 🛡️ Security Notice"
            echo "Antivirus warnings may occur and are likely **false positives**."
          } > RELEASE_NOTES.md

      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: 8.0.x

      # ---------------- WINDOWS ----------------
      - name: Build Windows
        run: |
          dotnet publish ${PROJECT_DIR}/Jellyfin2Samsung.csproj \
            -c $CONFIGURATION -r win-x64 -p:SelfContained=true \
            -o publish/win-x64

          mkdir -p dist
          (cd publish/win-x64 && zip -r "../../dist/${PRODUCT_NAME}-${VERSION_TAG}-win-x64.zip" .)

      # ---------------- LINUX ----------------
      - name: Build Linux
        run: |
          dotnet publish ${PROJECT_DIR}/Jellyfin2Samsung.csproj \
            -c $CONFIGURATION -r linux-x64 -p:SelfContained=true \
            -o publish/linux-x64

          tar -czf "dist/${PRODUCT_NAME}-${VERSION_TAG}-linux-x64.tar.gz" \
            -C publish/linux-x64 .

      # ---------------- LINUX ICON ----------------
      - name: Linux icon
        run: |
          sudo apt-get update
          sudo apt-get install -y librsvg2-bin
          rsvg-convert -w 256 -h 256 \
            jellyfin-tizen-logo.svg -o jellyfin.png

      # ---------------- DEB ----------------
      - name: Build .deb
        run: |
          sudo apt-get install -y dpkg-dev

          PKG=deb
          mkdir -p $PKG/opt/jellyfin2samsung \
                   $PKG/usr/share/{applications,icons/hicolor/256x256/apps}

          cp -R publish/linux-x64/. $PKG/opt/jellyfin2samsung/
          chmod +x $PKG/opt/jellyfin2samsung/Jellyfin2Samsung

          # 🔥 quick+dirty: allow writes where your app writes
          mkdir -p \
            $PKG/opt/jellyfin2samsung/Logs \
            $PKG/opt/jellyfin2samsung/Downloads \
            $PKG/opt/jellyfin2samsung/Assets/TizenSDB \
            $PKG/opt/jellyfin2samsung/Assets/Certificate
          chmod -R 777 \
            $PKG/opt/jellyfin2samsung/Logs \
            $PKG/opt/jellyfin2samsung/Downloads \
            $PKG/opt/jellyfin2samsung/Assets/TizenSDB \
            $PKG/opt/jellyfin2samsung/Assets/Certificate

          cp jellyfin.png $PKG/usr/share/icons/hicolor/256x256/apps/jellyfin2samsung.png

          cat > $PKG/usr/share/applications/jellyfin2samsung.desktop <<EOF
          [Desktop Entry]
          Name=Jellyfin2Samsung
          Exec=/opt/jellyfin2samsung/Jellyfin2Samsung
          Icon=jellyfin2samsung
          Type=Application
          Categories=Utility;
          EOF

          mkdir -p $PKG/DEBIAN
          cat > $PKG/DEBIAN/control <<EOF
          Package: jellyfin2samsung
          Version: ${VERSION}
          Architecture: amd64
          Maintainer: MadeByPatrick
          Description: Jellyfin2Samsung
          EOF

          dpkg-deb --build $PKG
          mv $PKG.deb dist/${PRODUCT_NAME}-${VERSION_TAG}-linux-x64.deb

      # ---------------- CREATE/UPDATE STABLE RELEASE ----------------
      - name: Create/Update GitHub Release (stable)
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ env.VERSION_TAG }}
          name: ${{ env.VERSION_TAG }}
          prerelease: false
          overwrite_files: true
          files: dist/*
          body_path: RELEASE_NOTES.md

# ======================================================
# MACOS (PER-ARCH CLI + APP + DMG)
# ======================================================
  macos-app:
    runs-on: macos-latest
    needs: stable-release
    if: needs.stable-release.result == 'success'

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.ref }}

      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: 8.0.x

      # ---------------- ICON ----------------
      - name: macOS icon
        run: |
          sips -s format png jellyfin-tizen-logo.svg --out jellyfin.png
          sips -z 1024 1024 jellyfin.png --out jellyfin.png

          mkdir icon.iconset
          for s in 16 32 128 256 512; do
            sips -z $s $s jellyfin.png --out icon.iconset/icon_${s}x${s}.png
            sips -z $((s*2)) $((s*2)) jellyfin.png --out icon.iconset/icon_${s}x${s}@2x.png
          done
          iconutil -c icns icon.iconset -o jellyfin.icns

      # ---------------- ARM64 ----------------
      - name: macOS ARM64 publish
        run: |
          dotnet publish ${PROJECT_DIR}/Jellyfin2Samsung.csproj \
            -c $CONFIGURATION -r osx-arm64 -p:SelfContained=true \
            -o publish/osx-arm64

          mkdir -p dist
          tar -czf \
            dist/${PRODUCT_NAME}-${{ needs.stable-release.outputs.VERSION_TAG }}-macos-arm64.tar.gz \
            -C publish/osx-arm64 .

          APP=Jellyfin2Samsung-arm64.app/Contents
          mkdir -p $APP/MacOS $APP/Resources
          cp -R publish/osx-arm64/* $APP/MacOS/
          chmod +x $APP/MacOS/Jellyfin2Samsung
          cp jellyfin.icns $APP/Resources/

          cat > $APP/Info.plist <<EOF
          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
            "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
          <plist version="1.0">
          <dict>
            <key>CFBundleName</key><string>Jellyfin2Samsung</string>
            <key>CFBundleExecutable</key><string>Jellyfin2Samsung</string>
            <key>CFBundleIdentifier</key><string>org.madebypatrick.jellyfin2samsung</string>
            <key>CFBundleVersion</key><string>${{ needs.stable-release.outputs.VERSION }}</string>
            <key>CFBundleShortVersionString</key><string>${{ needs.stable-release.outputs.VERSION }}</string>
            <key>CFBundlePackageType</key><string>APPL</string>
            <key>LSMinimumSystemVersion</key><string>11.0</string>

            <key>CFBundleIconFile</key><string>jellyfin.icns</string>
          </dict>
          </plist>
          EOF

          codesign --deep --force --sign - Jellyfin2Samsung-arm64.app

          rm -rf dmg-arm64
          mkdir -p dmg-arm64
          cp -R Jellyfin2Samsung-arm64.app dmg-arm64/Jellyfin2Samsung.app
          ln -s /Applications dmg-arm64/Applications
          hdiutil create \
            -volname Jellyfin2Samsung \
            -srcfolder dmg-arm64 \
            -format UDZO \
            dist/${PRODUCT_NAME}-${{ needs.stable-release.outputs.VERSION_TAG }}-macos-arm64.dmg

      # ---------------- INTEL ----------------
      - name: macOS Intel publish
        run: |
          dotnet publish ${PROJECT_DIR}/Jellyfin2Samsung.csproj \
            -c $CONFIGURATION -r osx-x64 -p:SelfContained=true \
            -o publish/osx-x64

          tar -czf \
            dist/${PRODUCT_NAME}-${{ needs.stable-release.outputs.VERSION_TAG }}-macos-x64.tar.gz \
            -C publish/osx-x64 .

          APP=Jellyfin2Samsung-x64.app/Contents
          mkdir -p $APP/MacOS $APP/Resources
          cp -R publish/osx-x64/* $APP/MacOS/
          chmod +x $APP/MacOS/Jellyfin2Samsung
          cp jellyfin.icns $APP/Resources/

          cat > $APP/Info.plist <<EOF
          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
            "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
          <plist version="1.0">
          <dict>
            <key>CFBundleName</key><string>Jellyfin2Samsung</string>
            <key>CFBundleExecutable</key><string>Jellyfin2Samsung</string>
            <key>CFBundleIdentifier</key><string>org.madebypatrick.jellyfin2samsung</string>
            <key>CFBundleVersion</key><string>${{ needs.stable-release.outputs.VERSION }}</string>
            <key>CFBundleShortVersionString</key><string>${{ needs.stable-release.outputs.VERSION }}</string>
            <key>CFBundlePackageType</key><string>APPL</string>
            <key>LSMinimumSystemVersion</key><string>11.0</string>

            <key>CFBundleIconFile</key><string>jellyfin.icns</string>
          </dict>
          </plist>
          EOF

          codesign --deep --force --sign - Jellyfin2Samsung-x64.app

          rm -rf dmg-x64
          mkdir -p dmg-x64
          cp -R Jellyfin2Samsung-x64.app dmg-x64/Jellyfin2Samsung.app
          ln -s /Applications dmg-x64/Applications
          hdiutil create \
            -volname Jellyfin2Samsung \
            -srcfolder dmg-x64 \
            -format UDZO \
            dist/${PRODUCT_NAME}-${{ needs.stable-release.outputs.VERSION_TAG }}-macos-x64.dmg

      # ---------------- UPLOAD MACOS ASSETS TO SAME STABLE RELEASE ----------------
      - name: Upload macOS assets to GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ needs.stable-release.outputs.VERSION_TAG }}
          name: ${{ needs.stable-release.outputs.VERSION_TAG }}
          prerelease: false
          overwrite_files: true
          files: dist/*
