name: Build and Docker Pipeline

on:
  push:
    branches: [main]
  workflow_dispatch:
  schedule:
    - cron: '0 2 * * *'  # 每天凌晨2点运行

env:
  REGISTRY: gitea.tailnet-68f9.ts.net
  IMAGE_NAME: ben/modelscope-builder

jobs:
  # 任务1: 环境检查和基础构建
  build-info:
    runs-on: ubuntu
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Runner Environment Info
        run: |
          echo "=== DSW Runner 环境信息 ==="
          echo "主机名: $(hostname)"
          echo "操作系统: $(uname -a)"
          echo "CPU 信息:"
          nproc
          cat /proc/cpuinfo | grep "model name" | head -1
          echo "内存信息:"
          free -h
          echo "磁盘空间:"
          df -h
          echo "当前时间: $(date)"
          echo "运行用户: $(whoami)"
          echo "工作目录: $(pwd)"

      - name: Check Tools Availability
        run: |
          echo "=== 检查可用工具 ==="
          echo "Git 版本:"
          git --version
          echo "Docker 版本:"
          docker --version || echo "Docker 未安装"
          echo "Go 版本:"
          go version || echo "Go 未安装"
          echo "Node.js 版本:"
          node --version || echo "Node.js 未安装"
          echo "Python 版本:"
          python3 --version || echo "Python3 未安装"
          echo "=== 网络连通性测试 ==="
          ping -c 2 gitea.tailnet-68f9.ts.net || echo "无法 ping Gitea"
          curl -s -o /dev/null -w "Gitea HTTP 状态: %{http_code}\n" https://gitea.tailnet-68f9.ts.net || echo "无法访问 Gitea HTTPS"

  # 任务2: 构建一个示例 Go 应用
  build-go-app:
    runs-on: ubuntu
    needs: build-info
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.21'

      - name: Create Sample Go App
        run: |
          mkdir -p ./sample-app
          cat > ./sample-app/main.go << 'EOF'
          package main

          import (
              "fmt"
              "net/http"
              "os"
              "time"
          )

          func main() {
              port := os.Getenv("PORT")
              if port == "" {
                  port = "8080"
              }

              http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
                  fmt.Fprintf(w, "Hello from DSW Runner! Time: %s\n", time.Now().Format(time.RFC3339))
              })

              http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
                  w.WriteHeader(http.StatusOK)
                  fmt.Fprintln(w, "OK")
              })

              fmt.Printf("Server starting on port %s...\n", port)
              if err := http.ListenAndServe(":"+port, nil); err != nil {
                  fmt.Printf("Server error: %v\n", err)
              }
          }
          EOF

          cat > ./sample-app/go.mod << 'EOF'
          module sample-app

          go 1.21
          EOF

      - name: Build Go App
        run: |
          cd ./sample-app
          echo "开始构建 Go 应用..."
          go build -v -o app main.go
          echo "构建完成！"
          ls -lh app
          file app

      - name: Test Binary
        run: |
          cd ./sample-app
          echo "测试二进制文件..."
          ./app &
          APP_PID=$!
          sleep 2
          curl -s http://localhost:8080/ || echo "服务测试失败"
          kill $APP_PID || true
          echo "测试完成"

      - name: Upload Build Artifact
        uses: actions/upload-artifact@v4
        with:
          name: go-app-binary
          path: ./sample-app/app
          retention-days: 7

  # 任务3: Docker 镜像构建（如果 Docker 可用）
  build-docker:
    runs-on: ubuntu
    needs: build-go-app
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Download Build Artifact
        uses: actions/download-artifact@v4
        with:
          name: go-app-binary
          path: ./sample-app/

      - name: Make Binary Executable
        run: chmod +x ./sample-app/app

      - name: Create Dockerfile
        run: |
          cat > ./sample-app/Dockerfile << 'EOF'
          FROM alpine:latest
          
          RUN apk add --no-cache ca-certificates
          
          WORKDIR /app
          COPY app /app/
          
          EXPOSE 8080
          
          ENV PORT=8080
          
          CMD ["./app"]
          EOF

      - name: Build Docker Image
        run: |
          if command -v docker &> /dev/null; then
            echo "Docker 可用，开始构建镜像..."
            cd ./sample-app
            docker build -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }} .
            docker tag ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }} ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
            echo "镜像构建完成！"
            docker images | grep ${{ env.IMAGE_NAME }}
          else
            echo "Docker 不可用，跳过镜像构建"
          fi

      - name: Test Docker Container
        run: |
          if command -v docker &> /dev/null; then
            echo "测试 Docker 容器..."
            docker run -d --name test-app -p 8081:8080 ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
            sleep 3
            curl -s http://localhost:8081/ || echo "容器测试失败"
            docker stop test-app
            docker rm test-app
            echo "容器测试完成"
          fi

      - name: Push Docker Image (if credentials available)
        run: |
          if command -v docker &> /dev/null; then
            echo "尝试推送镜像到仓库..."
            echo "注意: 需要配置 Docker 登录凭证"
            # docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
            # docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
          fi

  # 任务4: 清理和报告
  cleanup-and-report:
    runs-on: ubuntu
    needs: [build-info, build-go-app, build-docker]
    if: always()
    steps:
      - name: Generate Report
        run: |
          echo "=== 构建报告 ==="
          echo "工作流运行时间: ${{ github.run_duration }}"
          echo "触发事件: ${{ github.event_name }}"
          echo "提交 SHA: ${{ github.sha }}"
          echo "分支: ${{ github.ref }}"
          echo "=== 任务状态 ==="
          echo "build-info: ${{ needs.build-info.result }}"
          echo "build-go-app: ${{ needs.build-go-app.result }}"
          echo "build-docker: ${{ needs.build-docker.result }}"

      - name: Cleanup Docker
        run: |
          if command -v docker &> /dev/null; then
            echo "清理 Docker 资源..."
            docker system prune -f || true
            echo "清理完成"
          fi
