#!/bin/bash
# Load encrypted environment variables for OpenCode
# Works on macOS, Linux, and Windows (Git Bash)
# Usage: source commands/load-env.sh

if [ -n "$BASH_SOURCE" ]; then
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
elif [ -n "$ZSH_VERSION" ]; then
    SCRIPT_DIR="$(cd "$(dirname "${(%):-%x}")" && pwd)"
else
    SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
fi

INPUT_FILE="$SCRIPT_DIR/../.env.encrypted"

if [ ! -f "$INPUT_FILE" ]; then
    echo "❌ .env.encrypted not found. Run './commands/encrypt-env.sh' first."
    return 1 2>/dev/null || exit 1
fi

if [ -n "$OPENCODE_PASSPHRASE" ]; then
    PASSPHRASE="$OPENCODE_PASSPHRASE"
elif [ -f "$SCRIPT_DIR/../.env.passphrase" ]; then
    PASSPHRASE=$(cat "$SCRIPT_DIR/../.env.passphrase")
else
    if [ -n "$ZSH_VERSION" ]; then
        echo -n "🔑 Enter passphrase: "
        read -s PASSPHRASE
        echo ""
    else
        read -sp "🔑 Enter passphrase: " PASSPHRASE
        echo ""
    fi
fi

# Decrypt and export
DECRYPTED=$(openssl enc -aes-256-cbc -pbkdf2 -d -in "$INPUT_FILE" -pass pass:"$PASSPHRASE" 2>/dev/null)

if [ $? -ne 0 ]; then
    echo "❌ Incorrect passphrase or corrupted file."
    return 1 2>/dev/null || exit 1
fi

# Export each line as an environment variable from encrypted source
COUNT=0
while IFS= read -r line; do
    if [[ "$line" =~ ^[A-Za-z0-0_]+=.*$ ]]; then
        key="${line%%=*}"
        value="${line#*=}"
        export "$key=$value"
        COUNT=$((COUNT + 1))
    fi
done <<< "$DECRYPTED"

echo "✅ Loaded $COUNT environment variable(s) from .env.encrypted"

# Load .env.local if it exists
LOCAL_ENV="$SCRIPT_DIR/../.env.local"
if [ -f "$LOCAL_ENV" ]; then
    LOCAL_COUNT=0
    while IFS= read -r line || [ -n "$line" ]; do
        # Basic parsing for .env files (ignoring comments and empty lines)
        if [[ "$line" =~ ^[A-Za-z0-0_]+=.*$ ]]; then
            key="${line%%=*}"
            value="${line#*=}"
            # Trim potential quotes
            value="${value#[\"\']}"
            value="${value%[\"\']}"
            export "$key=$value"
            LOCAL_COUNT=$((LOCAL_COUNT + 1))
        fi
    done < "$LOCAL_ENV"
    echo "✅ Loaded $LOCAL_COUNT environment variable(s) from .env.local"
fi
