#!/bin/bash

# File header documentation
# @file run-deeplink-tests.sh
# @brief Automated deeplink testing script using generated JSON files and ADB
# @author Matthew Raymer
# @date $(date +%Y-%m-%d)

# Color definitions
BLUE='\033[0;34m'
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Parse command line arguments
TIMEOUT=10
TEST_MODE="execute"  # Default to execute mode

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

# Verify .generated directory exists
if [ ! -d .generated ]; then
    echo -e "${RED}Error: .generated directory not found${NC}"
    echo "Please run the DID generation script first"
    exit 1
fi

# Function to read and validate JSON files
validate_json_files() {
    local required_files=("test-env.sh" "claim_details.json" "contacts.json")
    for file in "${required_files[@]}"; do
        if [ ! -f ".generated/$file" ]; then
            echo -e "${RED}Error: Missing required file .generated/$file${NC}"
            return 1
        fi
    done
    return 0
}

# Function to URL encode string
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 execute or print deeplink
execute_deeplink() {
    local url="$1"
    local description="$2"
    
    echo -e "\n${BLUE}Testing: $description${NC}"
    echo -e "${YELLOW}Original URL: $url${NC}"
    
    if [ "$TEST_MODE" = "print" ]; then
        echo "---"
    else
        # Stop the app before executing the deep link
        adb shell am force-stop app.timesafari
        sleep 1  # Give it a moment to fully stop
        
        if adb shell am start -W -a android.intent.action.VIEW \
            -d "$url" \
            -c android.intent.category.BROWSABLE; then
            echo -e "${GREEN}Success: Deeplink executed${NC}"
            sleep "$TIMEOUT"
        else
            echo -e "${RED}Error: Failed to execute deeplink${NC}"
            return 1
        fi
    fi
}

# Main test sequence
main() {
    # Validate environment and files
    if ! validate_json_files; then
        exit 1
    fi
    
    # Source environment variables
    source .generated/test-env.sh
    
    # Load JSON data
    CLAIM_DETAILS=$(cat .generated/claim_details.json)
    CONTACTS=$(cat .generated/contacts.json)
    
    # 1. Claim-based deeplinks
    execute_deeplink "timesafari://claim/$(jq -r .claim_id <<< "$CLAIM_DETAILS")" \
        "Testing claim view"

    execute_deeplink "timesafari://claim-cert/$(jq -r .claim_id <<< "$CLAIM_DETAILS")" \
        "Testing claim certificate view"
        
    execute_deeplink "timesafari://claim-add-raw/$(jq -r .claim_id <<< "$CLAIM_DETAILS")" \
        "Testing raw claim addition"
    
    # 2. DID-based deeplinks
    execute_deeplink "timesafari://did/test" \
        "Testing DID view with test identifier"
    /d
    execute_deeplink "timesafari://did/$CONTACT1_DID" \
        "Testing DID view with contact DID"
        
    execute_deeplink "timesafari://contact-edit/$CONTACT1_DID" \
        "Testing contact editing"
    
    # 3. JSON-based deeplinks
    execute_deeplink "timesafari://contacts/import?contacts=$(jq -r @uri <<< "$CONTACTS")" \
        "Testing contacts import"
    
    echo -e "\n${GREEN}All deeplink tests completed${NC}"
}

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

# Execute main test sequence
main