name: CI

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]
  workflow_dispatch:  # Allow manual trigger

jobs:
  build:
    name: Build Flake
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - uses: cachix/install-nix-action@v23
        with:
          nix_path: nixpkgs=channel:nixos-unstable
          extra_nix_config: |
            experimental-features = nix-command flakes
      
      - name: Cache Nix store
        uses: actions/cache@v4
        with:
          path: |
            ~/.cache/nix
          key: ${{ runner.os }}-nix-${{ hashFiles('flake.lock') }}
          restore-keys: |
            ${{ runner.os }}-nix-
      
      - name: Build flake
        run: |
          nix flake check
          nix develop -c echo "Flake development environment builds successfully"
  lint:
    name: Lint
    runs-on: ubuntu-latest
    needs: [build]
    steps:
      - uses: actions/checkout@v4
      
      - uses: cachix/install-nix-action@v23
        with:
          nix_path: nixpkgs=channel:nixos-unstable
          extra_nix_config: |
            experimental-features = nix-command flakes
      
      - name: Cache Nix store
        uses: actions/cache@v4
        with:
          path: |
            ~/.cache/nix
          key: ${{ runner.os }}-nix-${{ hashFiles('flake.lock') }}
          restore-keys: |
            ${{ runner.os }}-nix-
      
      - name: Run lint
        run: |
          # Use nix develop to run linting tools defined in flake.nix
          nix develop --command lint

  test:
    name: Run Tests
    runs-on: ubuntu-latest
    needs: [build]
    steps:
      - uses: actions/checkout@v4
      
      - uses: cachix/install-nix-action@v23
        with:
          nix_path: nixpkgs=channel:nixos-unstable
          extra_nix_config: |
            experimental-features = nix-command flakes
      
      - name: Cache Nix store
        uses: actions/cache@v4
        with:
          path: |
            ~/.cache/nix
          key: ${{ runner.os }}-nix-${{ hashFiles('flake.lock') }}
          restore-keys: |
            ${{ runner.os }}-nix-
      
      - name: Cache Python virtual environment
        uses: actions/cache@v4
        with:
          path: .venv
          key: ${{ runner.os }}-venv-${{ hashFiles('requirements.txt') }}
          restore-keys: |
            ${{ runner.os }}-venv-
      
      - name: Setup and run tests
        run: |
          # Use nix develop to set up environment and run tests
          nix develop --command setup
          nix develop --command run-tests
          
      - name: Upload coverage reports to Codecov
        uses: codecov/codecov-action@v5
        with:
          token: ${{ secrets.CODECOV_TOKEN }}
          files: ./coverage.xml
          
      - name: Upload coverage artifact
        uses: actions/upload-artifact@v4
        with:
          name: coverage-report
          path: |
            ./htmlcov
            ./coverage.xml