name: CI

on:
  push:
    branches: ["master"]
  pull_request:
    branches: ["master"]

env:
  CARGO_TERM_COLOR: always

jobs:
  lint:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v5

      - uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy

      - uses: Swatinem/rust-cache@v2

      - name: Check formatting
        run: cargo fmt --all --check

      - name: Run clippy
        run: cargo clippy --all-targets --all-features -- -D warnings

  test:
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, macos-14, windows-latest]

    runs-on: ${{ matrix.os }}

    steps:
      - uses: actions/checkout@v5

      - uses: dtolnay/rust-toolchain@stable

      - uses: Swatinem/rust-cache@v2

      - name: Build debug binary
        run: cargo build --locked

      - name: Startup sanity check (Unix)
        if: runner.os != 'Windows'
        run: bash scripts/startup_smoke.sh target/debug/sxmc

      - name: Startup sanity check (Windows)
        if: runner.os == 'Windows'
        shell: pwsh
        run: |
          target\debug\sxmc.exe --version | Out-Null
          target\debug\sxmc.exe --help | Out-Null

      - name: Run tests
        run: cargo test --locked --all-targets

      - name: Run comprehensive sxmc script (Unix)
        if: runner.os != 'Windows'
        run: SXMC=target/debug/sxmc bash scripts/test-sxmc.sh --json /tmp/sxmc-test-results.json

      - name: Windows validation smoke
        if: runner.os == 'Windows'
        shell: pwsh
        run: |
          $doctor = target\debug\sxmc.exe doctor --format json | ConvertFrom-Json
          if (-not $doctor.root) { throw "doctor JSON missing root" }
          $compact = target\debug\sxmc.exe inspect cli cargo --compact --format json | ConvertFrom-Json
          if (-not $compact.subcommand_count) { throw "compact inspect missing subcommand_count" }
          $cache = target\debug\sxmc.exe inspect cache-stats --format json | ConvertFrom-Json
          if ($null -eq $cache.entry_count) { throw "cache stats missing entry_count" }

  smoke:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v5

      - uses: dtolnay/rust-toolchain@stable

      - uses: Swatinem/rust-cache@v2

      - name: Build debug binary
        run: cargo build --locked

      - name: Run cross-client smoke script
        run: bash scripts/smoke_test_clients.sh target/debug/sxmc tests/fixtures

      - name: Check npm wrapper files
        run: |
          node --check packaging/npm/bin/sxmc.js
          SXMC_NPM_SKIP_DOWNLOAD=1 node packaging/npm/scripts/install.mjs

  package:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v5

      - uses: dtolnay/rust-toolchain@stable

      - uses: Swatinem/rust-cache@v2

      - name: Verify package
        run: cargo package --locked
