name: Create GitHub Release

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:

permissions:
  contents: write

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

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

      - name: Install uv
        uses: astral-sh/setup-uv@v4

      - name: Install dependencies
        run: uv pip install --system -e ".[dev]"

      - name: Run tests
        run: uv run pytest tests/

      # Dashboard build disabled — not needed for daemon/server release
      # - name: Build dashboards
      #   run: |
      #     for dir in dashboards/*/; do
      #       cd "$dir" && npm ci && npm run build && cd -
      #     done

  release:
    needs: test
    runs-on: ubuntu-latest

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

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          generate_release_notes: true
          make_latest: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  publish:
    needs: release
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Install uv
        uses: astral-sh/setup-uv@v4

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

      - name: Build package
        run: uv build

      - name: Smoke test
        run: |
          uv pip install --system dist/*.whl
          python -c "from qc_trace import __version__; print(f'qc-trace {__version__}')"

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          password: ${{ secrets.PYPI_API_TOKEN }}

      - name: Update version_config in production DB
        run: |
          VERSION=$(python -c "from qc_trace import __version__; print(__version__)")
          PGPASSWORD="${{ secrets.PG_PASSWORD }}" psql \
            -h "${{ secrets.PG_HOST }}" \
            -p 5432 \
            -U "${{ secrets.PG_ADMIN }}" \
            -d qc_trace \
            -c "INSERT INTO version_config (key, value) VALUES ('latest_version', '${VERSION}') ON CONFLICT (key) DO UPDATE SET value = '${VERSION}';"
          echo "Updated version_config to ${VERSION}"
