name: Code Quality

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

jobs:
  quality-check:
    name: Quality Analysis
    runs-on: ubuntu-latest
    steps:
    - name: Checkout code
      uses: actions/checkout@v4
      with:
        fetch-depth: 0

    - name: Set up Go
      uses: actions/setup-go@v5
      with:
        go-version: '1.24'

    - name: Run go vet
      run: go vet ./...

    - name: Run go fmt check
      run: |
        if [ "$(gofmt -s -l . | wc -l)" -gt 0 ]; then
          echo "The following files are not formatted:"
          gofmt -s -l .
          exit 1
        fi

    - name: Run ineffassign
      run: |
        go install github.com/gordonklaus/ineffassign@latest
        ineffassign ./...

    - name: Run misspell
      run: |
        go install github.com/client9/misspell/cmd/misspell@latest
        misspell -error .

    - name: Run staticcheck
      run: |
        go install honnef.co/go/tools/cmd/staticcheck@latest
        staticcheck ./...

    - name: Check for TODO/FIXME comments
      run: |
        if grep -r "TODO\|FIXME" --include="*.go" .; then
          echo "Found TODO/FIXME comments. Please address them or add to issue tracker."
          exit 1
        fi

    - name: Run go mod tidy check
      run: |
        go mod tidy
        if [[ -n $(git status --porcelain go.mod go.sum) ]]; then
          echo "go.mod or go.sum is not tidy"
          git diff go.mod go.sum
          exit 1
        fi

    - name: Calculate code coverage
      run: |
        go test -coverprofile=coverage.out ./...
        go tool cover -func=coverage.out | grep total | awk '{print $3}' | sed 's/%//' > coverage.txt
        echo "Coverage: $(cat coverage.txt)%"

    - name: Check coverage threshold
      run: |
        COVERAGE=$(cat coverage.txt)
        THRESHOLD=80
        if (( $(echo "$COVERAGE < $THRESHOLD" | bc -l) )); then
          echo "Coverage $COVERAGE% is below threshold $THRESHOLD%"
          exit 1
        fi
        echo "Coverage $COVERAGE% meets threshold $THRESHOLD%"

    - name: SonarCloud Scan
      uses: SonarSource/sonarcloud-github-action@master
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
