# Disable set -e inherited from husky's sh -e wrapper.
# Git hooks run with stdout as a closed/broken pipe, causing echo to fail
# with "write error: Bad file descriptor". Under set -e this silently kills
# the entire hook. This script has explicit exit 1 calls for real failures.
set +e

# Redirect stdout to stderr so user-facing messages reach the terminal
# instead of git's closed stdout pipe.
exec 1>&2

# Run existing personal info check
node "$(dirname -- "$0")/../scripts/check-personal-paths.cjs"

# Check for build artifacts in src directories
echo "🔍 Checking for build artifacts in source directories..."

# Check for JS files in src/ (excluding proxy-bootstrap.js which is a legitimate source file)
if git diff --cached --name-only | grep -E '^src/.*\.(js|d\.ts|js\.map)$' | grep -v '^src/proxy/proxy-bootstrap.js$'; then
    echo ""
    echo "❌ Error: Build artifacts detected in src/ directory!"
    echo "   These files should not be committed:"
    git diff --cached --name-only | grep -E '^src/.*\.(js|d\.ts|js\.map)$' | grep -v '^src/proxy/proxy-bootstrap.js$'
    echo ""
    echo "💡 Run 'npm run clean' to remove build artifacts"
    echo "💡 Only TypeScript source files should be in src/"
    echo "💡 Exception: src/proxy/proxy-bootstrap.js is a legitimate JavaScript source file"
    exit 1
fi

# Check for JS files in packages/*/src/
if git diff --cached --name-only | grep -E '^packages/.*/src/.*\.(js|d\.ts|js\.map)$'; then
    echo ""
    echo "❌ Error: Build artifacts detected in package source directories!"
    echo "   These files should not be committed:"
    git diff --cached --name-only | grep -E '^packages/.*/src/.*\.(js|d\.ts|js\.map)$'
    echo ""
    echo "💡 Run 'npm run clean' to remove build artifacts"
    echo "💡 Only TypeScript source files should be in packages/*/src/"
    exit 1
fi

# Check for package tarballs
if git diff --cached --name-only | grep -E '\.tgz$'; then
    echo ""
    echo "❌ Error: Package tarball files detected!"
    echo "   These files should not be committed:"
    git diff --cached --name-only | grep -E '\.tgz$'
    echo ""
    echo "💡 Package tarballs are for local testing only"
    exit 1
fi

echo "✅ No build artifacts found in staged files"

# Docstar quick check (optional — runs only if docstar is installed)
# Full shadow + audit runs on pre-push instead.
if command -v docstar >/dev/null 2>&1; then
  echo "Docstar: Running quick check..."
  docstar check 2>/dev/null || true
fi
