# BEGIN: AI GUARDRAILS

# Skip pre-push checks in Claude Code remote environment
# These checks run in CI/CD anyway, and remote environments have limited resources
if [ "$CLAUDE_CODE_REMOTE" = "true" ]; then
  echo "ℹ️  Skipping pre-push checks (running in Claude Code remote environment)"
  exit 0
fi

# Detect package manager (check if tool is available before using it)
# Priority: bun > yarn > npm (bun first since package.json engines prefer it)
if ([ -f "bun.lockb" ] || [ -f "bun.lock" ]) && command -v bun >/dev/null 2>&1; then
  PACKAGE_MANAGER="bun"
  RUNNER="bun run"
elif [ -f "yarn.lock" ] && command -v yarn >/dev/null 2>&1; then
  PACKAGE_MANAGER="yarn"
  RUNNER="yarn"
elif [ -f "package-lock.json" ]; then
  PACKAGE_MANAGER="npm"
  RUNNER="npm run"
else
  # Default to npm if no lock file is found or tool is not available
  PACKAGE_MANAGER="npm"
  RUNNER="npm run"
fi

echo "📦 Using package manager: $PACKAGE_MANAGER"

# Run security audit
echo "🔒 Running security audit..."

if [ "$PACKAGE_MANAGER" = "yarn" ]; then
  # Check if jq is installed (required for yarn audit filtering)
  if ! command -v jq >/dev/null 2>&1; then
    echo ""
    echo "⚠️  WARNING: jq is not installed - required for yarn audit filtering"
    echo ""
    echo "To install jq:"
    echo "  macOS:    brew install jq"
    echo "  Windows:  choco install jq  # or scoop install jq"
    echo "  Linux:    apt-get install jq"
    echo ""
    echo "Continuing without security audit..."
    echo ""
  else
    # Excluding GHSA-5j98-mcp5-4vw2 (CVE-2025-64756): glob CLI command injection
    # This vulnerability only affects the glob CLI (--cmd flag), not library usage
    # We only use glob as a library through Babel and other tools - never invoke CLI
    # Risk: None - vulnerable code path is not executed in our application
    # Run yarn audit and filter for high/critical vulnerabilities (excluding glob CLI vuln)
    # Filter by both GHSA ID and CVE ID for robustness
    yarn audit --groups dependencies --json | jq -r 'select(.type == "auditAdvisory") | select(.data.advisory.severity == "high" or .data.advisory.severity == "critical") | select((.data.advisory.github_advisory_id == "GHSA-5j98-mcp5-4vw2" or (.data.advisory.cves | any(. == "CVE-2025-64756"))) | not) | .data.advisory' > high_vulns.json

    if [ -s high_vulns.json ]; then
      echo "❌ High or critical vulnerabilities found in production dependencies!"
      cat high_vulns.json
      rm high_vulns.json
      exit 1
    fi

    echo "✅ No high or critical vulnerabilities found in production dependencies (excluding known false positives)"
    rm -f high_vulns.json
  fi

elif [ "$PACKAGE_MANAGER" = "npm" ]; then
  # Run npm audit in JSON mode and filter out known false positives before failing.
  # npm audit lacks a native --ignore flag, so we parse JSON and exclude by GHSA ID.

  # Excluding GHSA-3ppc-4f35-3m26: minimatch ReDoS via repeated wildcards
  # Nested dep in aws-cdk-lib; fix requires minimatch v10 (incompatible with ^3.1.2)
  # Risk: None - dev-time CDK tooling, no production runtime exposure

  # Excluding GHSA-2g4f-4pwh-qvx6: ajv ReDoS with $data option
  # Nested dep in aws-cdk-lib and eslint; no fix available via npm
  # Risk: Low - $data option not used in this application

  AUDIT_JSON=$(npm audit --production --json 2>/dev/null || true)
  UNFIXED_HIGH=$(echo "$AUDIT_JSON" | jq '[.vulnerabilities | to_entries[] | select(.value.severity == "high" or .value.severity == "critical") | .value.via[] | select(type == "object") | .url | ltrimstr("https://github.com/advisories/")] | unique | map(select(. == "GHSA-3ppc-4f35-3m26" or . == "GHSA-2g4f-4pwh-qvx6" | not)) | length')
  if [ "$UNFIXED_HIGH" -gt 0 ]; then
    echo "⚠️ Security audit failed. Please fix high/critical vulnerabilities before pushing."
    exit 1
  fi
  echo "✅ No high or critical vulnerabilities found in production dependencies (excluding known false positives)"

elif [ "$PACKAGE_MANAGER" = "bun" ]; then
  # Excluding GHSA-5j98-mcp5-4vw2 (CVE-2025-64756): glob CLI command injection
  # This vulnerability only affects the glob CLI (--cmd flag), not library usage
  # We only use glob as a library through Babel and other tools - never invoke CLI

  # Excluding GHSA-8qq5-rm4j-mr97: node-tar path sanitization vulnerability
  # Nested dependency in @expo/cli - bun resolves to patched version but audit still flags it
  # Risk: Low - only affects tar extraction with malicious filenames, not our use case

  # Excluding GHSA-37qj-frw5-hhjh: fast-xml-parser RangeError DoS with numeric entities
  # Transitive dependency via @react-native-community/cli (Android/iOS build tooling)
  # Parent packages pin ^4.4.1; fix requires major version 5.x (incompatible)
  # Risk: None - CLI build tool, not a production runtime dependency

  # Excluding GHSA-3ppc-4f35-3m26: minimatch ReDoS via repeated wildcards
  # Transitive dependency in devDependencies (eslint, jest, nodemon, ts-morph, etc.)
  # Fix requires minimatch v10 which changes export shape (object vs function),
  # breaking test-exclude (used by Jest coverage). No production code path is affected.
  # Risk: None - only devDependency tooling, never processes untrusted user input

  # Excluding GHSA-jmr7-xgp7-cmfj: fast-xml-parser DoS through entity expansion in DOCTYPE
  # Transitive dependency via AWS SDK (@aws-sdk/xml-builder) and snowflake-sdk
  # Resolution to >=5.3.6 set in package.json but bun audit still flags intermediate ranges
  # Risk: Low - XML parsing of untrusted DOCTYPE content not in our code paths

  # Excluding GHSA-m7jm-9gc2-mpf2: fast-xml-parser entity encoding bypass via regex injection
  # Same transitive path as GHSA-jmr7-xgp7-cmfj (AWS SDK, snowflake-sdk)
  # Resolution to >=5.3.6 set in package.json but bun audit still flags intermediate ranges
  # Risk: Low - no untrusted XML with DOCTYPE entity names processed

  # Excluding GHSA-r6q2-hw4h-h46w: node-tar race condition via Unicode Ligature Collisions on macOS APFS
  # Transitive via @nestjs/apollo > @apollo/gateway > make-fetch-happen > cacache > tar
  # Resolution to ^7.5.8 set in package.json but bun audit still flags intermediate ranges
  # Risk: None - tar extraction not used in production runtime

  # Excluding GHSA-34x7-hfp2-rc4v: node-tar arbitrary file creation via hardlink path traversal
  # Same transitive path as GHSA-r6q2-hw4h-h46w
  # Risk: None - tar extraction not used in production runtime

  # Excluding GHSA-83g3-92jg-28cx: node-tar arbitrary file read/write via hardlink target escape
  # Same transitive path as GHSA-r6q2-hw4h-h46w
  # Risk: None - tar extraction not used in production runtime

  # Excluding GHSA-3h5v-q93c-6h6q: ws DoS when handling request with many HTTP headers
  # Transitive via @nestjs/graphql, graphql-ws, openai, serverless-offline, serverless-esbuild
  # Resolution to ^8.17.1 set in package.json but bun audit still flags intermediate ranges
  # Risk: Low - WebSocket servers behind API Gateway which limits headers

  if ! bun audit --audit-level=high --ignore GHSA-5j98-mcp5-4vw2 --ignore GHSA-8qq5-rm4j-mr97 --ignore GHSA-37qj-frw5-hhjh --ignore GHSA-3ppc-4f35-3m26 --ignore GHSA-jmr7-xgp7-cmfj --ignore GHSA-m7jm-9gc2-mpf2 --ignore GHSA-r6q2-hw4h-h46w --ignore GHSA-34x7-hfp2-rc4v --ignore GHSA-83g3-92jg-28cx --ignore GHSA-3h5v-q93c-6h6q; then
    echo "⚠️ Security audit failed. Please fix high/critical vulnerabilities before pushing."
    exit 1
  fi
  echo "✅ No high or critical vulnerabilities found in production dependencies"
fi

# Run slow lint rules - only if script exists
if jq -e '.scripts["lint:slow"]' package.json >/dev/null 2>&1; then
  echo "🐢 Running slow lint rules..."
  $RUNNER lint:slow
  if [ $? -ne 0 ]; then
    echo "❌ Slow lint rules failed. Please fix linting issues before pushing."
    exit 1
  fi
  echo "✅ Slow lint rules passed"
else
  echo "ℹ️  Skipping slow lint rules (lint:slow not configured)"
fi

# Run dead code detection (knip) - only if script exists
if jq -e '.scripts.knip' package.json >/dev/null 2>&1; then
  echo "🗑️ Running dead code detection (knip)..."
  $RUNNER knip
  if [ $? -ne 0 ]; then
    echo "❌ Dead code detected. Please remove unused exports/dependencies before pushing."
    echo ""
    echo "To auto-fix some issues, run: $RUNNER knip:fix"
    exit 1
  fi
  echo "✅ No dead code detected"
else
  echo "ℹ️  Skipping dead code detection (knip not configured)"
fi

# Run unit tests with coverage
echo "🧪 Running unit tests with coverage..."
$RUNNER test:cov
if [ $? -ne 0 ]; then
  echo "❌ Unit tests or coverage thresholds failed. Please fix before pushing."
  exit 1
fi

# Run integration tests
echo "🧪 Running integration tests..."
$RUNNER test:integration
if [ $? -ne 0 ]; then
  echo "❌ Integration tests failed. Please fix failing tests before pushing."
  exit 1
fi

# Run Lighthouse CI performance audit (only if installed)
# Disable Lighthouse beause it takes too long to run on push. Just let it run in ci/cd 
# Check if lighthouse:check script exists in package.json
# if ! grep -q '"lighthouse:check"' package.json 2>/dev/null; then
#   echo ""
#   echo "ℹ️  Skipping Lighthouse CI audit (not configured for this project)"
#   echo ""
# else
#   # Check if Chrome is available (required for Lighthouse)
#   CHROME_AVAILABLE=false
#   if command -v google-chrome >/dev/null 2>&1 || \
#      command -v google-chrome-stable >/dev/null 2>&1 || \
#      command -v chromium >/dev/null 2>&1 || \
#      command -v chromium-browser >/dev/null 2>&1 || \
#      [ -x "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" ]; then
#     CHROME_AVAILABLE=true
#   fi


#   if [ "$CHROME_AVAILABLE" = "false" ]; then
#     echo ""
#     echo "⚠️  WARNING: Chrome/Chromium not found - skipping Lighthouse CI audit"
#     echo ""
#     echo "To enable Lighthouse performance audits, install Chrome:"
#     echo "  macOS:    brew install --cask google-chrome"
#     echo "  Linux:    apt-get install chromium-browser  # or google-chrome-stable"
#     echo "  Windows:  choco install googlechrome"
#     echo ""
#     echo "Continuing without Lighthouse audit..."
#     echo ""
#   else
#     echo "🔦 Building web export for Lighthouse..."
#     $RUNNER export:web
#     if [ $? -ne 0 ]; then
#       echo "❌ Web export failed. Please fix build errors before pushing."
#       exit 1
#     fi

#     echo "🔦 Running Lighthouse CI performance audit..."
#     LIGHTHOUSE_OUTPUT=$($RUNNER lighthouse:check 2>&1)
#     LIGHTHOUSE_EXIT=$?
#     echo "$LIGHTHOUSE_OUTPUT"

#     # Extract report URL from output
#     REPORT_URL=$(echo "$LIGHTHOUSE_OUTPUT" | grep -o 'https://storage.googleapis.com/[^ ]*\.html' | head -1)

#     if [ $LIGHTHOUSE_EXIT -ne 0 ]; then
#       echo ""
#       echo "❌ Lighthouse CI performance audit failed!"
#       echo ""
#       echo "Your changes caused performance regressions that exceed the allowed thresholds."
#       echo ""
#       if [ -n "$REPORT_URL" ]; then
#         echo "📊 View full report: $REPORT_URL"
#         echo ""
#       fi
#       echo "Common fixes:"
#       echo "  • Bundle size too large → Remove unused dependencies, add code splitting"
#       echo "  • LCP/FCP too slow → Optimize images, reduce render-blocking resources"
#       echo "  • CLS too high → Add explicit dimensions to images/containers"
#       echo "  • Too much unused JS → Implement lazy loading for non-critical code"
#       echo ""
#       echo "See lighthouserc.js for threshold details."
#       echo ""
#       exit 1
#     fi
#     echo "✅ Lighthouse CI performance audit passed"
#   fi
# fi

exit 0

# END: AI GUARDRAILS