name: CI

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

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  # Stage 1: Quick checks (parallel)
  fmt:
    uses: ./.github/workflows/cargo-fmt-nightly.yml

  check:
    uses: ./.github/workflows/cargo-check.yml

  check-simd:
    uses: ./.github/workflows/cargo-check-simd.yml

  check-no-std:
    uses: ./.github/workflows/cargo-check-no-std.yml

  # Stage 2: Linting
  clippy:
    needs: check
    uses: ./.github/workflows/cargo-clippy.yml

  doc:
    needs: check
    uses: ./.github/workflows/cargo-doc.yml

  # Stage 3: Testing
  test:
    needs: clippy
    uses: ./.github/workflows/cargo-test.yml

  test-simd:
    needs: check-simd
    uses: ./.github/workflows/cargo-test-simd.yml

  # Stage 4: Coverage
  coverage:
    needs: test
    uses: ./.github/workflows/coverage.yml
    secrets:
      CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}

  test-results:
    needs: test
    uses: ./.github/workflows/test-results.yml
    secrets:
      CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}

  # Stage 5: Changelog
  changelog:
    needs: [test, doc]
    permissions:
      contents: write
    uses: ./.github/workflows/changelog.yml
    with:
      enabled: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/dev') && !contains(github.event.head_commit.message, 'chore') }}

  # Stage 6: Publish
  publish:
    needs: [test, test-simd, coverage]
    uses: ./.github/workflows/publish.yml
    with:
      enabled: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
    secrets:
      CRATESIO: ${{ secrets.CRATESIO }}

  # Stage 7: Release
  release:
    needs: [publish, changelog]
    permissions:
      contents: write
    uses: ./.github/workflows/release.yml
    with:
      enabled: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}

  # Final gate
  ci-success:
    if: always()
    needs: [fmt, check, check-simd, check-no-std, clippy, doc, test, test-simd, coverage]
    runs-on: ubuntu-latest
    steps:
      - if: contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')
        run: exit 1
      - run: echo "All CI checks passed!"

  # Cleanup
  cleanup:
    if: always()
    needs: ci-success
    permissions:
      actions: write
    uses: ./.github/workflows/cleanup.yml
