#!/bin/bash

# Husky Setup Script for Common Platform
# Sets up pre-commit hooks with HUSKY_ENABLED flag support

set -e

echo "🐶 Setting up Husky git hooks for common platform..."

# Create .husky directory if it doesn't exist
mkdir -p .husky

# Create pre-commit hook with HUSKY_ENABLED flag
cat > .husky/pre-commit << 'EOF'
#!/usr/bin/env sh

# Ensure hooks run from repo root (we intentionally do not source Husky internals).
ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"
if [ -n "$ROOT" ]; then
  cd "$ROOT" || exit 1
fi

# Prefer local binaries (prettier/lint-staged/etc.)
export PATH="$PWD/node_modules/.bin:$PATH"

# Check if Husky is disabled via environment variable
if [ "$HUSKY_ENABLED" = "false" ]; then
  echo "⚠️  Husky disabled via HUSKY_ENABLED=false"
  echo "💡 To re-enable: unset HUSKY_ENABLED or export HUSKY_ENABLED=true"
  exit 0
fi

echo "🔐 Scanning staged changes for secrets..."
bash scripts/secret-scan-staged.sh

echo "🐶 Running pre-commit hooks for common platform..."

# Run lint-staged on staged files
pnpm exec lint-staged
EOF

# Create pre-push hook with HUSKY_ENABLED flag
cat > .husky/pre-push << 'EOF'
#!/usr/bin/env sh

# Ensure hooks run from repo root (we intentionally do not source Husky internals).
ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"
if [ -n "$ROOT" ]; then
  cd "$ROOT" || exit 1
fi

# Prefer local binaries (if needed in future).
export PATH="$PWD/node_modules/.bin:$PATH"

# Check if Husky is disabled via environment variable
if [ "$HUSKY_ENABLED" = "false" ]; then
  echo "⚠️  Husky disabled via HUSKY_ENABLED=false"
  echo "💡 To re-enable: unset HUSKY_ENABLED or export HUSKY_ENABLED=true"
  exit 0
fi

echo "🔐 Scanning tracked files for secrets before push..."
bash scripts/secret-scan-repo.sh
EOF

# Make the hook executable
chmod +x .husky/pre-commit
chmod +x .husky/pre-push

echo "✅ Pre-commit hook created successfully!"
echo "✅ Pre-push hook created successfully!"
echo ""
echo "📖 Usage:"
echo "   Normal commit:     git commit -m 'feat: add feature'"
echo "   Disable hooks:     export HUSKY_ENABLED=false"
echo "   Enable hooks:      export HUSKY_ENABLED=true"
echo "   One-time bypass:   git commit --no-verify"
