#!/bin/bash

# Verify required environment variables are set
required_vars=(
    "CONTACT1_DID"
    "CONTACT1_KEY"
    "CONTACT2_DID"
    "CONTACT2_KEY"
    "ISSUER_DID"
    "ISSUER_KEY"
    "CONTACTS_JSON"
)

for var in "${required_vars[@]}"; do
    if [ -z "${!var}" ]; then
        echo "Error: $var is not set"
        echo "Please run: source .generated/test-env.sh"
        exit 1
    fi
done

# Color definitions
BLUE='\033[0;34m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
BOLD='\033[1m'

# Parse command line arguments
TIMEOUT=5
ALL_TESTS=false
TEST_MODE=${TEST_MODE:-execute}  # Default to execute mode

while getopts "t:a" opt; do
    case $opt in
        t) TIMEOUT=$OPTARG ;;
        a) ALL_TESTS=true ;;
        \?) echo "Invalid option: -$OPTARG" >&2; exit 1 ;;
    esac
done

# Check for adb and connected devices
if [ "$TEST_MODE" = "execute" ]; then
    if ! command -v adb >/dev/null 2>&1; then
        echo "Warning: adb not found, switching to print mode"
        TEST_MODE=print
    elif [ -z "$(adb devices | grep -v List | grep device)" ]; then
        echo "Warning: no devices/emulators found, switching to print mode"
        TEST_MODE=print
    fi
fi

# Function to encode URL parameters
urlencode() {
    local string="${1}"
    local strlen=${#string}
    local encoded=""
    local pos c o

    for (( pos=0 ; pos<strlen ; pos++ )); do
        c=${string:$pos:1}
        case "$c" in
            [-_.~a-zA-Z0-9] ) o="${c}" ;;
            * )               printf -v o '%%%02x' "'$c"
        esac
        encoded+="${o}"
    done
    echo "${encoded}"
}

# Function to print section header
print_header() {
    echo -e "\n${BOLD}${1}${NC}"
    echo -e "${BOLD}$(printf '=%.0s' {1..50})${NC}\n"
}

# Function to handle deep links
handle_deeplink() {
    local url="$1"
    local color="$2"
    local encoded_url=$(urlencode "$url")
    
    if [ "$TEST_MODE" = "print" ]; then
        echo -e "${color}Deep Link URL:${NC}"
        echo -e "${color}$url${NC}"
        echo -e "${color}Encoded URL:${NC}"
        echo -e "${color}$encoded_url${NC}"
        echo "---"
    else
        echo -e "${color}Opening: $url${NC}"
        adb shell am start -a android.intent.action.VIEW -d "$encoded_url"
        sleep "$TIMEOUT"
    fi
}

# Generate a test JWT for claims
TEST_JWT=$(./test-scripts/did_generator.sh | grep "Created JWT:" | cut -d' ' -f3)

echo -e "${BOLD}Running deep link tests (mode: $TEST_MODE)...${NC}"

# 1. Basic routes
print_header "Basic Routes"
handle_deeplink "timesafari://claim-cert/$TEST_JWT" $BLUE
handle_deeplink "timesafari://claim-add-raw/$TEST_JWT?claim=$(urlencode '{"type":"test"}')&claimJwtId=$TEST_JWT" $BLUE

# 2. Contact import routes
print_header "Contact Import Routes"
handle_deeplink "timesafari://contacts/import?contacts=$(urlencode "$CONTACTS_JSON")" $GREEN
handle_deeplink "timesafari://contacts" $GREEN

# 3. Contact management routes
print_header "Contact Management Routes"
handle_deeplink "timesafari://contact-edit?did=$CONTACT1_DID" $YELLOW
handle_deeplink "timesafari://contact-edit?did=$CONTACT2_DID" $YELLOW

if [ "$ALL_TESTS" = true ]; then
    # 4. Claims and verification routes
    print_header "Claims and Verification Routes"
    handle_deeplink "timesafari://verify?issuer=$ISSUER_DID" $PURPLE
    handle_deeplink "timesafari://claims?contact=$CONTACT1_DID" $PURPLE
    
    # 5. Project routes
    print_header "Project Routes"
    handle_deeplink "timesafari://projects" $CYAN
    handle_deeplink "timesafari://project-edit?id=test-project" $CYAN
fi

echo -e "\n${BOLD}Deep link tests completed${NC}"