name: Test particle-os CI/CD

on:
  workflow_dispatch:  # Manual trigger

jobs:
  test-cicd:
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        
      - name: Setup Go
        uses: actions/setup-go@v4
        with:
          go-version: '1.21'
          
      - name: Build particle-os
        run: |
          cd bib
          go build -o particle-os cmd/particle_os/main.go
          cd ..
          
      - name: Test CI/CD mode
        run: |
          # Test quiet mode (should show minimal output)
          echo "Testing quiet mode..."
          if sudo ./bib/particle-os build --json --quiet --clean recipes/debian-test.yml 2>&1 | grep -q "INFO"; then
            echo "❌ FAIL: Quiet mode still shows INFO logs"
            exit 1
          else
            echo "✅ PASS: Quiet mode suppresses INFO logs"
          fi
          
      - name: Test JSON output
        run: |
          echo "Testing JSON output..."
          BUILD_OUTPUT=$(sudo ./bib/particle-os build --json --quiet --clean recipes/debian-test.yml 2>&1 | grep -A 20 '^{' | head -n 20)
          
          # Check if output contains JSON
          if echo "$BUILD_OUTPUT" | grep -q '{'; then
            echo "✅ PASS: Output contains JSON"
            
            # Check for required fields
            REQUIRED_FIELDS=("recipe" "base_image" "stages" "output_formats" "image_path" "work_directory" "build_time" "exit_code")
            for field in "${REQUIRED_FIELDS[@]}"; do
              if echo "$BUILD_OUTPUT" | grep -q "\"$field\""; then
                echo "✅ PASS: JSON contains $field field"
              else
                echo "❌ FAIL: JSON missing $field field"
                exit 1
              fi
            done
          else
            echo "❌ FAIL: Output is not JSON format"
            echo "Output: $BUILD_OUTPUT"
            exit 1
          fi
          
      - name: Test exit codes
        run: |
          echo "Testing exit codes..."
          if sudo ./bib/particle-os build --json --quiet --clean recipes/debian-test.yml > /dev/null 2>&1; then
            echo "✅ PASS: Build command returns appropriate exit code"
          else
            echo "❌ FAIL: Build command failed unexpectedly"
            exit 1
          fi
          
      - name: Success
        run: |
          echo "🎉 All CI/CD tests passed!"
          echo "particle-os is ready for production CI/CD use!"
