#!/bin/bash
# Validate .env files for common issues including invisible Unicode characters
# This script can be run before deployment to catch potential problems

set -e

ENV_FILE="${1:-.env}"

if [ ! -f "$ENV_FILE" ]; then
    echo "✓ No $ENV_FILE file found (using environment variables or defaults)"
    exit 0
fi

if [ $# -lt 1 ]; then
    echo "Usage: $(basename "$0") [.env file path]"
    echo "Example: $(basename "$0") .env"
    exit 1
fi

echo "Validating $ENV_FILE..."
echo ""

# Check for invisible Unicode characters
FOUND_ISSUES=0

# Check for U+200E (Left-to-Right Mark) - E2 80 8E
if grep -q $'\xE2\x80\x8E' "$ENV_FILE" 2>/dev/null; then
    echo "✗ Found U+200E (Left-to-Right Mark) invisible character"
    grep -n $'\xE2\x80\x8E' "$ENV_FILE" | head -5
    FOUND_ISSUES=1
fi

# Check for U+200F (Right-to-Left Mark) - E2 80 8F
if grep -q $'\xE2\x80\x8F' "$ENV_FILE" 2>/dev/null; then
    echo "✗ Found U+200F (Right-to-Left Mark) invisible character"
    grep -n $'\xE2\x80\x8F' "$ENV_FILE" | head -5
    FOUND_ISSUES=1
fi

# Check for U+200B (Zero Width Space) - E2 80 8B
if grep -q $'\xE2\x80\x8B' "$ENV_FILE" 2>/dev/null; then
    echo "✗ Found U+200B (Zero Width Space) invisible character"
    grep -n $'\xE2\x80\x8B' "$ENV_FILE" | head -5
    FOUND_ISSUES=1
fi

# Check for BOM (Byte Order Mark) - EF BB BF
if grep -q $'\xEF\xBB\xBF' "$ENV_FILE" 2>/dev/null; then
    echo "✗ Found BOM (Byte Order Mark) at start of file"
    FOUND_ISSUES=1
fi

# Check for other directional formatting characters
for code in $'\xE2\x80\xAA' $'\xE2\x80\xAB' $'\xE2\x80\xAC' $'\xE2\x80\xAD' $'\xE2\x80\xAE'; do
    if grep -q "$code" "$ENV_FILE" 2>/dev/null; then
        echo "✗ Found directional formatting invisible character"
        FOUND_ISSUES=1
        break
    fi
done

# Check for Windows line endings (CRLF) if file command is available
if command -v file >/dev/null 2>&1; then
    if file "$ENV_FILE" | grep -q CRLF 2>/dev/null; then
        echo "⚠ Warning: File has Windows line endings (CRLF)"
        echo "  This may cause issues on Linux. Consider converting to LF."
    fi
fi

# Check for trailing spaces on variable definitions
if grep -E '^[A-Z_]+[[:space:]]+=' "$ENV_FILE" >/dev/null 2>&1; then
    echo "⚠ Warning: Found spaces before '=' in variable definitions"
    grep -n -E '^[A-Z_]+[[:space:]]+=' "$ENV_FILE"
fi

# Check for spaces in variable names
if grep -E '^[A-Z_]+[[:space:]]+[^=]*=' "$ENV_FILE" >/dev/null 2>&1; then
    echo "⚠ Warning: Possible spaces in variable names"
fi

if [ $FOUND_ISSUES -eq 0 ]; then
    echo "✓ No invisible Unicode characters found"
    echo "✓ File looks clean!"
    exit 0
else
    echo ""
    echo "----------------------------------------"
    echo "Issues found! Run the following to fix:"
    echo "  ./scripts/clean-env.sh $ENV_FILE"
    echo "----------------------------------------"
    exit 1
fi
