name: Build and Publish

on:
  workflow_dispatch:
    inputs:
      publish_pypi:
        description: 'Pubblicare su PyPI (true) o compilare eseguibili? (false)'
        required: true
        default: 'false'
        type: choice
        options:
          - 'true'
          - 'false'
  push:
    tags:
      - "v*.*"
    branches:
      - main

jobs:
  publish:
    if: startsWith(github.ref_name, 'v') || (github.event_name == 'workflow_dispatch' && github.event.inputs.publish_pypi == 'true')
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Get the latest tag
        id: get_latest_tag
        run: echo "latest_tag=$(git describe --tags --abbrev=0)" >> $GITHUB_ENV

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.13'

      - name: Install packaging dependencies
        run: |
          python -m pip install --upgrade pip
          python -m pip install --upgrade setuptools>=61.0.0 wheel twine build

      - name: Build package
        run: python -m build

      - name: Upload to PyPI
        env:
          TWINE_USERNAME: __token__
          TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
        run: twine upload dist/*

  build:
    if: startsWith(github.ref_name, 'v') || (github.event_name == 'workflow_dispatch' && github.event.inputs.publish_pypi == 'false') || github.event_name == 'push'

    strategy:
      matrix:
        include:
          - os: windows-2025
            arch: x64
            artifact_name: StreamingCommunity_win_2025_x64
            executable: StreamingCommunity_win_2025_x64.exe
            separator: ';'

          - os: windows-2022
            arch: x64
            artifact_name: StreamingCommunity_win_2022_x64
            executable: StreamingCommunity_win_2022_x64.exe
            separator: ';'

          - os: macos-26
            arch: arm64
            artifact_name: StreamingCommunity_mac_26_arm64
            executable: StreamingCommunity_mac_26_arm64
            separator: ':'

          - os: macos-15
            arch: x64
            artifact_name: StreamingCommunity_mac_15_x64
            executable: StreamingCommunity_mac_15_x64
            separator: ':'

          - os: macos-15
            arch: arm64
            artifact_name: StreamingCommunity_mac_15_arm64
            executable: StreamingCommunity_mac_15_arm64
            separator: ':'

          - os: macos-14
            arch: x64
            artifact_name: StreamingCommunity_mac_14_x64
            executable: StreamingCommunity_mac_14_x64
            separator: ':'

          - os: macos-14
            arch: arm64
            artifact_name: StreamingCommunity_mac_14_arm64
            executable: StreamingCommunity_mac_14_arm64
            separator: ':'

          - os: ubuntu-24.04
            arch: x64
            artifact_name: StreamingCommunity_linux_24_04_x64
            executable: StreamingCommunity_linux_24_04_x64
            separator: ':'

          - os: ubuntu-22.04
            arch: x64
            artifact_name: StreamingCommunity_linux_22_04_x64
            executable: StreamingCommunity_linux_22_04_x64
            separator: ':'

    runs-on: ${{ matrix.os }}
    defaults:
      run:
        shell: bash

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Get the latest tag
        id: get_latest_tag
        shell: pwsh
        run: |
          $latestTag = git describe --tags --abbrev=0
          echo "latest_tag=$latestTag" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.12'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          python -m pip install --upgrade certifi
          python -m pip install -r requirements.txt
          python -m pip install pyinstaller

      - name: Build executable with PyInstaller
        shell: bash
        run: |
          pyinstaller --onefile \
          --hidden-import=sqlite3 \
          --collect-binaries sqlite3 \
          --hidden-import=ua_generator \
          --hidden-import=bs4 \
          --hidden-import=httpx \
          --hidden-import=rich \
          --hidden-import=rich._unicode_data \
          --collect-all rich \
          --hidden-import=unidecode \
          --hidden-import=jsbeautifier \
          --hidden-import=editorconfig \
          --hidden-import=six \
          --hidden-import=pathvalidate \
          --hidden-import=xml.etree.ElementTree \
          --hidden-import=pywidevine \
          --hidden-import=pyplayready \
          --hidden-import=curl_cffi \
          --hidden-import=_cffi_backend \
          --collect-all curl_cffi \
          --additional-hooks-dir=pyinstaller/hooks \
          --add-data "StreamingCommunity${{ matrix.separator }}StreamingCommunity" \
          --name=${{ matrix.artifact_name }} test_run.py

      - name: Upload executable
        uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.artifact_name }}
          path: dist/${{ matrix.executable }}

      - name: Delete old release assets (only on push to main)
        if: github.event_name == 'push' && github.ref == 'refs/heads/main'
        continue-on-error: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

        run: |
          LATEST_TAG="${{ env.latest_tag }}"
          ASSET_NAME="${{ matrix.executable }}"
          
          # Get release ID by tag
          RELEASE_ID=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \
            "https://api.github.com/repos/${{ github.repository }}/releases/tags/$LATEST_TAG" | \
            jq -r '.id')
          
          if [ "$RELEASE_ID" != "null" ]; then
            # Trova e cancella l'asset esistente
            ASSET_ID=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \
              "https://api.github.com/repos/${{ github.repository }}/releases/$RELEASE_ID/assets" | \
              jq -r ".[] | select(.name == \"$ASSET_NAME\") | .id")
            
            if [ "$ASSET_ID" != "" ]; then
              curl -X DELETE -H "Authorization: token $GITHUB_TOKEN" \
                "https://api.github.com/repos/${{ github.repository }}/releases/assets/$ASSET_ID"
            fi
          fi

      - name: Upload to latest release (only on push to main)
        if: github.event_name == 'push' && github.ref == 'refs/heads/main'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          LATEST_TAG="${{ env.latest_tag }}"
          gh release upload "$LATEST_TAG" "dist/${{ matrix.executable }}" --clobber

      - name: Create or update release
        if: startsWith(github.ref, 'refs/tags/')
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ github.ref_name }}
          files: dist/${{ matrix.executable }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}