name: CI

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1

jobs:
  # ── Native builds: Windows, macOS, Linux ────────────────────────────────────
  native:
    name: Native — ${{ matrix.os }}
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
          - os: windows-latest
            target: x86_64-pc-windows-msvc
          - os: macos-latest
            target: aarch64-apple-darwin

    steps:
      - uses: actions/checkout@v4

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Cache Cargo registry and build
        uses: Swatinem/rust-cache@v2

      # Linux: install Bevy's system dependencies (X11, Wayland, audio)
      - name: Install Linux system dependencies
        if: matrix.os == 'ubuntu-latest'
        run: |
          sudo apt-get update
          sudo apt-get install -y \
            libasound2-dev \
            libudev-dev \
            libwayland-dev \
            libxkbcommon-dev \
            libx11-dev \
            libxi-dev \
            pkg-config

      - name: Check (fast compile check)
        run: cargo check --workspace --target ${{ matrix.target }}

      - name: Build (debug)
        run: cargo build --workspace --target ${{ matrix.target }}

      - name: Run tests
        run: cargo test --workspace --target ${{ matrix.target }}

      - name: Clippy
        run: cargo clippy --workspace --target ${{ matrix.target }} -- -D warnings

  # ── WASM / Web build ─────────────────────────────────────────────────────────
  wasm:
    name: WASM — Web
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - name: Install Rust toolchain + WASM target
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: wasm32-unknown-unknown

      - name: Cache Cargo
        uses: Swatinem/rust-cache@v2

      - name: Install Trunk
        uses: jetli/trunk-action@v0.5.0

      - name: Check WASM compile
        run: >
          cargo check
          --target wasm32-unknown-unknown
          -p sylpheed-viewer
          -p sylpheed-formats

      - name: Build WASM release with Trunk
        run: trunk build --release

      - name: Upload WASM dist artifact
        uses: actions/upload-artifact@v4
        with:
          name: web-dist
          path: dist/

  # ── Format check ─────────────────────────────────────────────────────────────
  fmt:
    name: Formatting
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt
      - run: cargo fmt --all -- --check
