#!/bin/bash
#
# DSS Code Quality Verification Script
# Runs automated checks to ensure code quality standards before commits
#
# Enforces standards from: .knowledge/dss-coding-standards.json
#
# Thresholds:
#   - Inline event handlers: 0 (ZERO TOLERANCE)
#   - Inline styles: ≤10 (dynamic values only)
#   - Console statements: ≤10 (use logger utility)
#   - File size: ≤100KB
#   - Syntax errors: 0 (ZERO TOLERANCE)
#
# Only checks files that are staged for commit (git diff --cached)
#

set -e

echo "🔍 Running DSS Code Quality Checks..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Track if any checks fail
FAILED=0

# Get list of staged JS files in admin-ui/js/ and server/src/
STAGED_JS_FILES=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '(admin-ui/js/.*\.js|server/src/.*\.js)$' || true)

# If no JS files are staged, skip quality checks
if [ -z "$STAGED_JS_FILES" ]; then
  echo "ℹ️  No JavaScript files in commit, skipping quality checks."
  exit 0
fi

echo "📄 Checking $(echo "$STAGED_JS_FILES" | wc -w) staged JavaScript files..."

# 1. Check for inline event handlers (onmouseover, onclick, etc.)
# ZERO TOLERANCE per DSS coding standards
echo ""
echo "📋 Checking for inline event handlers..."
INLINE_EVENTS=$(echo "$STAGED_JS_FILES" | xargs grep -n "on\(click\|mouseover\|mouseout\|keydown\|keyup\|load\|submit\)=" 2>/dev/null || true)
if [ -n "$INLINE_EVENTS" ]; then
  echo "$INLINE_EVENTS"
  echo -e "${RED}✗ CRITICAL: Inline event handlers found in staged files (ZERO TOLERANCE)${NC}"
  echo -e "${RED}   Use event delegation with addEventListener instead${NC}"
  echo -e "${RED}   See: .knowledge/dss-coding-standards.json > event_handling${NC}"
  FAILED=1
fi

# 2. Check for excessive inline styles
# Threshold: ≤10 per DSS coding standards (exceptions for dynamic values only)
echo ""
echo "🎨 Checking for excessive inline styles..."
INLINE_STYLE_COUNT=$(echo "$STAGED_JS_FILES" | xargs grep -n 'style="' 2>/dev/null | wc -l)
if [ "$INLINE_STYLE_COUNT" -gt 10 ]; then
  echo -e "${RED}✗ Found $INLINE_STYLE_COUNT inline style attributes in staged files (threshold: ≤10)${NC}"
  echo -e "${RED}   Extract styles to Shadow DOM <style> blocks${NC}"
  echo -e "${RED}   See: .knowledge/dss-coding-standards.json > style_management${NC}"
  FAILED=1
else
  echo -e "${GREEN}✓ Inline styles within acceptable range ($INLINE_STYLE_COUNT/10)${NC}"
fi

# 3. Check for missing ARIA attributes on buttons
echo ""
echo "♿ Checking accessibility..."
BUTTON_ISSUES=$(echo "$STAGED_JS_FILES" | xargs grep -n '<button' 2>/dev/null | grep -v 'aria-label\|type="button"' | head -5 || true)
if [ -n "$BUTTON_ISSUES" ]; then
  echo "$BUTTON_ISSUES"
  echo -e "${YELLOW}⚠️  Warning: Some buttons may be missing accessibility attributes (aria-label or type).${NC}"
else
  echo -e "${GREEN}✓ Button accessibility looks good${NC}"
fi

# 4. Check for console.log statements (except in designated logging files)
# Threshold: ≤10 per DSS coding standards (use logger utility instead)
echo ""
echo "🪵  Checking for debug console statements..."
DEBUG_LOGS=$(echo "$STAGED_JS_FILES" | grep -v "logger\.js" | xargs grep -n 'console\.log\|console\.warn' 2>/dev/null | wc -l)
if [ "$DEBUG_LOGS" -gt 10 ]; then
  echo -e "${YELLOW}⚠️  Warning: Found $DEBUG_LOGS console.log/warn statements in staged files (threshold: ≤10)${NC}"
  echo -e "${YELLOW}   Replace with logger utility: logger.debug() / logger.info()${NC}"
  echo -e "${YELLOW}   See: admin-ui/js/utils/logger.js${NC}"
fi

# 5. Check for TODO/FIXME comments
echo ""
echo "📝 Checking for TODO/FIXME comments..."
TODO_COUNT=$(echo "$STAGED_JS_FILES" | xargs grep -n 'TODO\|FIXME' 2>/dev/null | wc -l)
if [ "$TODO_COUNT" -gt 0 ]; then
  echo -e "${YELLOW}ℹ️  Info: Found $TODO_COUNT TODO/FIXME comments in staged files${NC}"
fi

# 6. Check JavaScript syntax (if node is available)
echo ""
echo "🔧 Checking JavaScript syntax..."
if command -v node &> /dev/null; then
  SYNTAX_ERRORS=0
  for file in $STAGED_JS_FILES; do
    if ! node --check "$file" 2>/dev/null; then
      echo -e "${RED}✗ Syntax error in: $file${NC}"
      SYNTAX_ERRORS=$((SYNTAX_ERRORS + 1))
      FAILED=1
    fi
  done

  if [ "$SYNTAX_ERRORS" -eq 0 ]; then
    echo -e "${GREEN}✓ All staged JavaScript files have valid syntax${NC}"
  else
    echo -e "${RED}✗ Found $SYNTAX_ERRORS staged files with syntax errors${NC}"
  fi
else
  echo -e "${YELLOW}⚠️  Node.js not found, skipping syntax check${NC}"
fi

# 7. Check for hardcoded credentials or API keys
echo ""
echo "🔐 Checking for potential secrets..."
SECRETS=$(echo "$STAGED_JS_FILES" | xargs grep -n "apiKey\|api_key\|password\|secret\|token" 2>/dev/null | grep -v "//\|/\*" | grep "=" | head -5 || true)
if [ -n "$SECRETS" ]; then
  echo "$SECRETS"
  echo -e "${RED}⚠️  Warning: Potential hardcoded secrets found in staged files. Review carefully!${NC}"
else
  echo -e "${GREEN}✓ No obvious hardcoded secrets detected${NC}"
fi

# 8. Check for proper Shadow DOM usage in web components (only for component files)
echo ""
echo "🌓 Checking Shadow DOM usage..."
STAGED_COMPONENTS=$(echo "$STAGED_JS_FILES" | grep "admin-ui/js/components/" || true)
if [ -n "$STAGED_COMPONENTS" ]; then
  COMPONENT_COUNT=$(echo "$STAGED_COMPONENTS" | grep "extends HTMLElement" | wc -l)
  SHADOW_COUNT=$(echo "$STAGED_COMPONENTS" | xargs grep -l "attachShadow" 2>/dev/null | wc -l || echo "0")
  echo -e "${GREEN}ℹ️  Staged: $COMPONENT_COUNT web components, $SHADOW_COUNT using Shadow DOM${NC}"
else
  echo -e "${GREEN}ℹ️  No component files in staged changes${NC}"
fi

# 9. Check file sizes
echo ""
echo "📦 Checking file sizes..."
LARGE_STAGED=()
for file in $STAGED_JS_FILES; do
  if [ -f "$file" ] && [ $(stat -f%z "$file" 2>/dev/null || stat -c%s "$file" 2>/dev/null) -gt 102400 ]; then
    LARGE_STAGED+=("$file")
  fi
done
if [ ${#LARGE_STAGED[@]} -gt 0 ]; then
  echo -e "${YELLOW}⚠️  Warning: Large JavaScript files in staged changes (>100KB):${NC}"
  printf '%s\n' "${LARGE_STAGED[@]}"
else
  echo -e "${GREEN}✓ All staged JavaScript files are reasonably sized${NC}"
fi

# Summary
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [ "$FAILED" -eq 0 ]; then
  echo -e "${GREEN}✅ Quality checks passed!${NC}"
  exit 0
else
  echo -e "${RED}❌ Quality checks failed. Please fix the errors above.${NC}"
  exit 1
fi
