name: Simple DSW Build Test

on:
  push:
    branches: [main]
  workflow_dispatch:

jobs:
  # 任务1: 基础环境检查
  check-env:
    runs-on: ubuntu
    steps:
      - name: Print Environment
        run: |
          echo "========================================"
          echo "DSW Runner 环境检查"
          echo "========================================"
          echo "时间: $(date)"
          echo "主机名: $(hostname)"
          echo "当前目录: $(pwd)"
          echo "用户: $(whoami)"
          echo ""
          echo "=== 系统信息 ==="
          uname -a
          echo ""
          echo "=== CPU ==="
          nproc
          cat /proc/cpuinfo | grep "model name" | head -1
          echo ""
          echo "=== 内存 ==="
          free -h
          echo ""
          echo "=== 磁盘 ==="
          df -h
          echo "========================================"

  # 任务2: 检查工具
  check-tools:
    runs-on: ubuntu
    needs: check-env
    steps:
      - name: Check Available Tools
        run: |
          echo "=== 检查可用工具 ==="
          
          echo -n "Git: "
          git --version 2>/dev/null || echo "未安装"
          
          echo -n "Docker: "
          docker --version 2>/dev/null || echo "未安装"
          
          echo -n "Go: "
          go version 2>/dev/null || echo "未安装"
          
          echo -n "Node.js: "
          node --version 2>/dev/null || echo "未安装"
          
          echo -n "Python3: "
          python3 --version 2>/dev/null || echo "未安装"
          
          echo -n "Make: "
          make --version 2>/dev/null | head -1 || echo "未安装"
          
          echo -n "GCC: "
          gcc --version 2>/dev/null | head -1 || echo "未安装"
          
          echo "=== PATH ==="
          echo $PATH

  # 任务3: 网络测试（只测内网）
  network-test:
    runs-on: ubuntu
    needs: check-env
    steps:
      - name: Network Connectivity
        run: |
          echo "=== 网络连通性测试（仅内网） ==="
          
          echo "测试访问 Gitea:"
          curl -s -o /dev/null -w "状态码: %{http_code}\n" --max-time 10 https://gitea.tailnet-68f9.ts.net || echo "❌ 无法访问"
          
          echo ""
          echo "测试 DNS 解析:"
          nslookup gitea.tailnet-68f9.ts.net || echo "DNS 解析失败"

  # 任务4: 实际工作 - 本地构建
  build-sample:
    runs-on: ubuntu
    needs: [check-env, check-tools]
    steps:
      - name: Build Simple C Program
        run: |
          echo "=== 编译简单 C 程序 ==="
          cat > /tmp/hello.c << 'EOF'
          #include <stdio.h>
          #include <stdlib.h>
          
          int main() {
              printf("Hello from DSW Runner!\n");
              printf("Build time: %s\n", __TIME__);
              printf("Date: %s\n", __DATE__);
              return 0;
          }
          EOF
          
          if command -v gcc &> /dev/null; then
            gcc -o /tmp/hello /tmp/hello.c && /tmp/hello
          else
            echo "GCC 未安装，跳过编译"
          fi

      - name: Python Script Test
        run: |
          echo "=== 运行 Python 脚本 ==="
          python3 << 'EOF'
          import platform
          import datetime
          import os
          
          print("Python 系统信息:")
          print(f"  系统: {platform.system()}")
          print(f"  版本: {platform.release()}")
          print(f"  机器: {platform.machine()}")
          print(f"  处理器: {platform.processor()}")
          print(f"  Python 版本: {platform.python_version()}")
          print(f"  当前时间: {datetime.datetime.now()}")
          print(f"  工作目录: {os.getcwd()}")
          print(f"  用户: {os.getenv('USER', 'unknown')}")
          print("\n✅ Python 脚本执行成功!")
          EOF

      - name: Create Artifact
        run: |
          echo "=== 创建构建产物 ==="
          mkdir -p /tmp/artifacts
          echo "Build completed at $(date)" > /tmp/artifacts/build-info.txt
          echo "Runner: $(hostname)" >> /tmp/artifacts/build-info.txt
          echo "User: $(whoami)" >> /tmp/artifacts/build-info.txt
          cat /tmp/artifacts/build-info.txt

  # 任务5: Docker 测试（如果可用，使用本地镜像）
  docker-test:
    runs-on: ubuntu
    needs: check-tools
    steps:
      - name: Test Docker
        run: |
          echo "=== Docker 测试 ==="
          if command -v docker &> /dev/null; then
            echo "Docker 版本:"
            docker --version
            
            echo ""
            echo "Docker 信息:"
            docker info 2>/dev/null | head -20 || echo "无法获取 Docker 信息"
            
            echo ""
            echo "本地镜像列表:"
            docker images 2>/dev/null || echo "无法列出镜像"
            
            echo ""
            echo "运行中的容器:"
            docker ps 2>/dev/null || echo "无法列出容器"
          else
            echo "Docker 未安装，跳过测试"
          fi

  # 任务6: 压力测试 - 计算密集型任务
  stress-test:
    runs-on: ubuntu
    needs: [check-env, check-tools]
    steps:
      - name: CPU Stress Test
        run: |
          echo "=== CPU 压力测试 ==="
          python3 << 'EOF'
          import time
          import multiprocessing
          
          def cpu_task(n):
              """计算斐波那契数列"""
              if n <= 1:
                  return n
              a, b = 0, 1
              for _ in range(2, n + 1):
                  a, b = b, a + b
              return b
          
          print(f"CPU 核心数: {multiprocessing.cpu_count()}")
          print("开始计算...")
          
          start = time.time()
          # 计算第 35 个斐波那契数 1000 次
          for i in range(1000):
              result = cpu_task(35)
          
          elapsed = time.time() - start
          print(f"计算完成! 耗时: {elapsed:.2f} 秒")
          print(f"结果: {result}")
          print("✅ CPU 压力测试通过!")
          EOF

      - name: Memory Test
        run: |
          echo "=== 内存测试 ==="
          python3 << 'EOF'
          import sys
          
          # 创建大列表测试内存
          print("分配 100MB 内存...")
          big_list = [0] * (100 * 1024 * 1024 // 8)  # 100MB
          print(f"列表大小: {len(big_list)} 个元素")
          print(f"内存使用: ~100MB")
          print("✅ 内存测试通过!")
          EOF

  # 任务7: 总结报告
  report:
    runs-on: ubuntu
    needs: [check-env, check-tools, network-test, build-sample, docker-test, stress-test]
    if: always()
    steps:
      - name: Generate Report
        run: |
          echo "========================================"
          echo "DSW Runner 测试报告"
          echo "========================================"
          echo "所有任务已完成！"
          echo "运行时间: $(date)"
          echo "========================================"
