#!/usr/bin/env bash
set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

WORKFLOW_FILE=${1:-.github/workflows/ci.yml}
ERRORS=0
WARNINGS=0

echo "=== GitHub Actions Workflow Validator ==="
echo

if [[ ! -f "$WORKFLOW_FILE" ]]; then
    echo -e "${RED}✗ Workflow file not found: $WORKFLOW_FILE${NC}"
    exit 1
fi

# Check SHA pinning
echo "[1/3] Checking action pinning..."
if grep -E "uses:.*@v[0-9]" "$WORKFLOW_FILE" >/dev/null 2>&1; then
    echo -e "${RED}✗ Actions using tags instead of SHA${NC}"
    ((ERRORS++))
else
    echo -e "${GREEN}✓ Actions properly SHA-pinned${NC}"
fi

# Check permissions
echo "[2/3] Checking permissions..."
if grep -q "permissions:" "$WORKFLOW_FILE"; then
    echo -e "${GREEN}✓ Permissions defined${NC}"
else
    echo -e "${YELLOW}⚠ No permissions defined${NC}"
    ((WARNINGS++))
fi

# Check for secrets in workflow
echo "[3/3] Checking for hardcoded secrets..."
if grep -iE "(password|token|key|secret).*:" "$WORKFLOW_FILE" | grep -v "secrets\." >/dev/null 2>&1; then
    echo -e "${RED}✗ Potential hardcoded secrets${NC}"
    ((ERRORS++))
else
    echo -e "${GREEN}✓ No hardcoded secrets${NC}"
fi

echo
echo "=== Summary ==="
if [[ $ERRORS -eq 0 ]] && [[ $WARNINGS -eq 0 ]]; then
    echo -e "${GREEN}✓ All checks passed${NC}"
    exit 0
elif [[ $ERRORS -eq 0 ]]; then
    echo -e "${YELLOW}⚠ $WARNINGS warning(s)${NC}"
    exit 0
else
    echo -e "${RED}✗ $ERRORS error(s), $WARNINGS warning(s)${NC}"
    exit 1
fi
