#!/bin/bash
#
# GitHub Authentication Fix Test Script
# Tests the implemented authentication fixes in remote-deploy.sh
#

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} ✅ $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} ⚠️  $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} ❌ $1"
}

log_debug() {
    echo -e "${PURPLE}[DEBUG]${NC} 🔍 $1"
}

echo "🧪 GitHub Authentication Fix Test"
echo "================================="
echo ""

# Check if GitHub token is available
if [[ -z "${GITHUB_TOKEN:-}" ]]; then
    if [[ -f ".github-pat" ]]; then
        log_info "Loading GitHub token from .github-pat file"
        if GITHUB_TOKEN=$(cat .github-pat 2>/dev/null | tr -d '\n\r') && [[ -n "$GITHUB_TOKEN" ]]; then
            export GITHUB_TOKEN
            log_success "GitHub token loaded successfully"
        else
            log_error "Failed to load GitHub token from .github-pat file"
            exit 1
        fi
    else
        log_error "No GitHub token available (GITHUB_TOKEN or .github-pat file)"
        exit 1
    fi
else
    log_success "GitHub token available from environment"
fi

echo ""

# Test 1: Validate git credential format fixes
log_info "Test 1: Validating git credential format fixes"

# Check if the fixes are present in remote-deploy.sh
log_debug "Checking for oauth2 credential format in remote-deploy.sh"
if grep -q "https://oauth2:\$GITHUB_TOKEN@github.com" scripts/vm/remote-deploy.sh; then
    log_success "✓ Found oauth2 credential format fix"
else
    log_error "✗ oauth2 credential format fix not found"
fi

log_debug "Checking for alternative username credential format"
if grep -q "https://pacnpal:\$GITHUB_TOKEN@github.com" scripts/vm/remote-deploy.sh; then
    log_success "✓ Found alternative username credential format fix"
else
    log_error "✗ Alternative username credential format fix not found"
fi

echo ""

# Test 2: Validate authenticated URL fallback
log_info "Test 2: Validating authenticated URL fallback implementation"

log_debug "Checking for authenticated URL creation logic"
if grep -q "auth_url.*oauth2.*GITHUB_TOKEN" scripts/vm/remote-deploy.sh; then
    log_success "✓ Found authenticated URL creation logic"
else
    log_error "✗ Authenticated URL creation logic not found"
fi

log_debug "Checking for git clone fallback with authenticated URL"
if grep -q "git clone.*auth_url" scripts/vm/remote-deploy.sh; then
    log_success "✓ Found git clone fallback with authenticated URL"
else
    log_error "✗ Git clone fallback with authenticated URL not found"
fi

echo ""

# Test 3: Validate enhanced error handling
log_info "Test 3: Validating enhanced error handling"

log_debug "Checking for git fetch fallback logic"
if grep -q "fetch_success.*false" scripts/vm/remote-deploy.sh; then
    log_success "✓ Found git fetch fallback logic"
else
    log_error "✗ Git fetch fallback logic not found"
fi

log_debug "Checking for clone success tracking"
if grep -q "clone_success.*false" scripts/vm/remote-deploy.sh; then
    log_success "✓ Found clone success tracking"
else
    log_error "✗ Clone success tracking not found"
fi

echo ""

# Test 4: Test credential format generation
log_info "Test 4: Testing credential format generation"

# Test oauth2 format
oauth2_format="https://oauth2:${GITHUB_TOKEN}@github.com"
log_debug "OAuth2 format: https://oauth2:***@github.com"
if [[ "$oauth2_format" =~ ^https://oauth2:.+@github\.com$ ]]; then
    log_success "✓ OAuth2 credential format is valid"
else
    log_error "✗ OAuth2 credential format is invalid"
fi

# Test username format
username_format="https://pacnpal:${GITHUB_TOKEN}@github.com"
log_debug "Username format: https://pacnpal:***@github.com"
if [[ "$username_format" =~ ^https://pacnpal:.+@github\.com$ ]]; then
    log_success "✓ Username credential format is valid"
else
    log_error "✗ Username credential format is invalid"
fi

echo ""

# Test 5: Test authenticated URL generation
log_info "Test 5: Testing authenticated URL generation"

REPO_URL="https://github.com/pacnpal/thrillwiki_django_no_react.git"
auth_url=$(echo "$REPO_URL" | sed "s|https://github.com/|https://oauth2:${GITHUB_TOKEN}@github.com/|")

log_debug "Original URL: $REPO_URL"
log_debug "Authenticated URL: ${auth_url/oauth2:${GITHUB_TOKEN}@/oauth2:***@}"

if [[ "$auth_url" =~ ^https://oauth2:.+@github\.com/pacnpal/thrillwiki_django_no_react\.git$ ]]; then
    log_success "✓ Authenticated URL generation is correct"
else
    log_error "✗ Authenticated URL generation is incorrect"
fi

echo ""

# Test 6: Test git credential file format
log_info "Test 6: Testing git credential file format"

# Create test credential files
test_dir="/tmp/github-auth-test-$$"
mkdir -p "$test_dir"

# Test oauth2 format
echo "https://oauth2:${GITHUB_TOKEN}@github.com" > "$test_dir/credentials-oauth2"
chmod 600 "$test_dir/credentials-oauth2"

# Test username format  
echo "https://pacnpal:${GITHUB_TOKEN}@github.com" > "$test_dir/credentials-username"
chmod 600 "$test_dir/credentials-username"

# Validate file permissions
if [[ "$(stat -c %a "$test_dir/credentials-oauth2" 2>/dev/null || stat -f %A "$test_dir/credentials-oauth2" 2>/dev/null)" == "600" ]]; then
    log_success "✓ Credential file permissions are secure (600)"
else
    log_warning "⚠ Credential file permissions may not be secure"
fi

# Clean up test files
rm -rf "$test_dir"

echo ""

# Test 7: Validate deployment script syntax
log_info "Test 7: Validating deployment script syntax"

log_debug "Checking remote-deploy.sh syntax"
if bash -n scripts/vm/remote-deploy.sh; then
    log_success "✓ remote-deploy.sh syntax is valid"
else
    log_error "✗ remote-deploy.sh has syntax errors"
fi

echo ""

# Test 8: Check for logging improvements
log_info "Test 8: Validating logging improvements"

log_debug "Checking for enhanced debug logging"
if grep -q "deploy_debug.*Setting up git credential helper" scripts/vm/remote-deploy.sh; then
    log_success "✓ Found enhanced debug logging for git setup"
else
    log_warning "⚠ Enhanced debug logging not found"
fi

log_debug "Checking for authenticated URL debug logging"
if grep -q "deploy_debug.*Using authenticated URL format" scripts/vm/remote-deploy.sh; then
    log_success "✓ Found authenticated URL debug logging"
else
    log_warning "⚠ Authenticated URL debug logging not found"
fi

echo ""

# Summary
echo "🎯 TEST SUMMARY"
echo "==============="

# Count successful tests
total_tests=8
passed_tests=0

# Check each test result (simplified for this demo)
if grep -q "oauth2.*GITHUB_TOKEN.*github.com" scripts/vm/remote-deploy.sh; then
    ((passed_tests++))
fi

if grep -q "auth_url.*oauth2.*GITHUB_TOKEN" scripts/vm/remote-deploy.sh; then
    ((passed_tests++))
fi

if grep -q "fetch_success.*false" scripts/vm/remote-deploy.sh; then
    ((passed_tests++))
fi

if grep -q "clone_success.*false" scripts/vm/remote-deploy.sh; then
    ((passed_tests++))
fi

if [[ "$oauth2_format" =~ ^https://oauth2:.+@github\.com$ ]]; then
    ((passed_tests++))
fi

if [[ "$auth_url" =~ ^https://oauth2:.+@github\.com/pacnpal/thrillwiki_django_no_react\.git$ ]]; then
    ((passed_tests++))
fi

if bash -n scripts/vm/remote-deploy.sh; then
    ((passed_tests++))
fi

if grep -q "deploy_debug.*Setting up git credential helper" scripts/vm/remote-deploy.sh; then
    ((passed_tests++))
fi

echo "Tests passed: $passed_tests/$total_tests"

if [[ $passed_tests -eq $total_tests ]]; then
    log_success "All tests passed! GitHub authentication fix is ready"
    echo ""
    echo "✅ PRIMARY ISSUE FIXED: Git credential format now includes username (oauth2)"
    echo "✅ SECONDARY ISSUE FIXED: Authenticated URL fallback implemented"
    echo "✅ ENHANCED ERROR HANDLING: Multiple retry mechanisms added"
    echo "✅ IMPROVED LOGGING: Better debugging information available"
    echo ""
    echo "The deployment should now successfully clone the GitHub repository!"
    exit 0
else
    log_warning "Some tests failed. Please review the implementation."
    exit 1
fi