name: Run Unit Tests

on:
  push:
    branches:
      - main
      - develop
  pull_request:

jobs:
  test:
    runs-on: phpunit_test
    container: docker.xuanyuan.me/xeden3/php8.1-node-gitea-runner:v1.2

    steps:
      - name: Checkout code
        uses: http://119.91.43.128:3003/james/checkout@v4

      - name: Install dependencies
        run: |
          # 安装依赖
          composer global show phpunit/phpunit
          composer install --no-interaction --prefer-dist
          composer require workerman/workerman

      - name: Run PHPUnit tests
        run: |
          XDEBUG_MODE=coverage vendor/bin/phpunit --configuration phpunit.xml --verbose

      - name: Show coverage.xml
        run: |
          cat coverage.xml

      - name: Check coverage threshold (100% required)
        run: |
          # 提取项目级别的覆盖率数据
          total_statements=$(xmlstarlet sel -t -v "//project/metrics/@statements" coverage.xml)
          covered_statements=$(xmlstarlet sel -t -v "//project/metrics/@coveredstatements" coverage.xml)

          total_methods=$(xmlstarlet sel -t -v "//project/metrics/@methods" coverage.xml)
          covered_methods=$(xmlstarlet sel -t -v "//project/metrics/@coveredmethods" coverage.xml)

          if [ -z "$total_statements" ] || [ -z "$covered_statements" ] || \
             [ -z "$total_methods" ] || [ -z "$covered_methods" ]; then
            echo "❌ 无法提取覆盖率数据，请检查 coverage.xml 格式"
            exit 1
          fi

          # 计算覆盖率百分比
          statement_coverage=$(echo "scale=2; $covered_statements / $total_statements * 100" | bc)
          method_coverage=$(echo "scale=2; $covered_methods / $total_methods * 100" | bc)

          echo "📈 行覆盖率: $statement_coverage%"
          echo "📉 函数覆盖率: $method_coverage%"

          # 提取未覆盖的行号 statement level
          uncovered_lines=$(xmlstarlet sel -t -m "//file/line[@type='stmt' and @count=0]" -v "concat(../@name, '()', ':', @num)" coverage.xml | sort -u)

          # 输出未覆盖的行
          if [ -n "$uncovered_lines" ]; then
            echo -e "❌ 以下行未被覆盖：\n$uncovered_lines"
          fi


          # 检查是否达标
          if [ "$(echo "$statement_coverage < 99.9" | bc)" -eq 1 ]; then
            echo "❌ 行覆盖率未达到 100%"
            exit 1
          fi

          if [ "$(echo "$method_coverage < 99.9" | bc)" -eq 1 ]; then
            echo "❌ 函数覆盖率未达到 100%"
            exit 1
          fi

          echo "✅ 行覆盖率和函数覆盖率均达标"