name: Release Build & Publish

on:
  release:
    types: [published]

jobs:
  release:
    name: Release on ${{ matrix.os }}
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
        python-version: ["3.9"]

    steps:
    - name: Checkout repository
      uses: actions/checkout@v2

    - name: Set up Python ${{ matrix.python-version }}
      uses: actions/setup-python@v2
      with:
        python-version: ${{ matrix.python-version }}

    - name: Set up Miniconda
      uses: conda-incubator/setup-miniconda@v2
      with:
        miniconda-version: "latest"
        auto-activate-base: false
        python-version: ${{ matrix.python-version }}

    - name: Install Conda dependencies
      run: |
        conda install -y conda-build anaconda-client twine setuptools wheel

    # OS-specific GDAL setup
    - name: Install GDAL system dependencies (Ubuntu)
      if: runner.os == 'Linux'
      run: |
        sudo add-apt-repository ppa:ubuntugis/ubuntugis-unstable
        sudo apt-get update
        sudo apt-get install -y gdal-bin libgdal-dev

    - name: Install GDAL system dependencies (macOS)
      if: runner.os == 'macOS'
      run: |
        brew update
        brew install gdal
        brew upgrade gdal

    - name: Install GDAL with Conda (Windows)
      if: runner.os == 'Windows'
      run: |
        conda install -c conda-forge gdal pytest h5py

    - name: Install dependencies and polsartools pip package
      run: |
        python -m pip install --upgrade pip
        python -m pip install -r requirements.txt

    - name: Build pip package
      run: |
        python setup.py sdist bdist_wheel

    - name: Build Conda package
      run: |
        conda build ./conda-recipe

    - name: Upload to PyPI
      env:
        TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
        TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
      run: |
        python -m pip install twine
        twine upload dist/*

    - name: Upload to Anaconda
      env:
        ANACONDA_API_TOKEN: ${{ secrets.ANACONDA_API_TOKEN }}
      run: |
        anaconda upload --skip-existing $(conda build ./conda-recipe --output)
