#!/bin/bash
#
# GitHub Authentication Diagnosis Script
# Validates the specific authentication issues identified
#

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
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"
}

echo "🔍 GitHub Authentication Diagnosis"
echo "=================================="
echo ""

# Test 1: Check if GITHUB_TOKEN is available
log_info "Test 1: Checking GitHub token availability"
if [[ -n "${GITHUB_TOKEN:-}" ]]; then
    log_success "GITHUB_TOKEN is available in environment"
    echo "Token length: ${#GITHUB_TOKEN} characters"
else
    log_error "GITHUB_TOKEN is not available in environment"
    
    # Check for token file
    if [[ -f ".github-pat" ]]; then
        log_info "Found .github-pat file, attempting to load..."
        if GITHUB_TOKEN=$(cat .github-pat 2>/dev/null | tr -d '\n\r') && [[ -n "$GITHUB_TOKEN" ]]; then
            log_success "Loaded GitHub token from .github-pat file"
            export GITHUB_TOKEN
        else
            log_error "Failed to load token from .github-pat file"
        fi
    else
        log_error "No .github-pat file found"
    fi
fi

echo ""

# Test 2: Validate git credential helper format
log_info "Test 2: Testing git credential formats"

if [[ -n "${GITHUB_TOKEN:-}" ]]; then
    # Test current (incorrect) format
    log_info "Current format: https://\$GITHUB_TOKEN@github.com"
    echo "https://$GITHUB_TOKEN@github.com" > /tmp/test-credentials-bad
    log_warning "This format is MISSING username component - will fail"
    
    # Test correct format
    log_info "Correct format: https://oauth2:\$GITHUB_TOKEN@github.com"
    echo "https://oauth2:$GITHUB_TOKEN@github.com" > /tmp/test-credentials-good
    log_success "This format includes oauth2 username - should work"
    
    # Test alternative format
    log_info "Alternative format: https://pacnpal:\$GITHUB_TOKEN@github.com"
    echo "https://pacnpal:$GITHUB_TOKEN@github.com" > /tmp/test-credentials-alt
    log_success "This format uses actual username - should work"
    
    rm -f /tmp/test-credentials-*
else
    log_error "Cannot test credential formats without GITHUB_TOKEN"
fi

echo ""

# Test 3: Test repository URL formats
log_info "Test 3: Testing repository URL formats"

REPO_URL="https://github.com/pacnpal/thrillwiki_django_no_react.git"
log_info "Current repo URL: $REPO_URL"
log_warning "This is plain HTTPS - requires separate authentication"

if [[ -n "${GITHUB_TOKEN:-}" ]]; then
    AUTH_URL="https://oauth2:${GITHUB_TOKEN}@github.com/pacnpal/thrillwiki_django_no_react.git"
    log_info "Authenticated repo URL: https://oauth2:*****@github.com/..."
    log_success "This URL embeds credentials - should work without git config"
fi

echo ""

# Test 4: Simulate the exact deployment scenario
log_info "Test 4: Simulating deployment git credential configuration"

if [[ -n "${GITHUB_TOKEN:-}" ]]; then
    # Simulate current (broken) approach
    log_info "Current approach (lines 1276 in remote-deploy.sh):"
    echo "  git config --global credential.helper store"
    echo "  echo 'https://\$GITHUB_TOKEN@github.com' > ~/.git-credentials"
    log_error "This will fail because git expects format: https://user:token@host"
    
    echo ""
    
    # Show correct approach
    log_info "Correct approach should be:"
    echo "  git config --global credential.helper store"
    echo "  echo 'https://oauth2:\$GITHUB_TOKEN@github.com' > ~/.git-credentials"
    log_success "This includes the required username component"
else
    log_error "Cannot simulate without GITHUB_TOKEN"
fi

echo ""

# Test 5: Check deployment script logic flow
log_info "Test 5: Analyzing deployment script logic"

log_info "Issue found in scripts/vm/remote-deploy.sh:"
echo "  Line 1276: echo 'https://\$GITHUB_TOKEN@github.com' > ~/.git-credentials"
log_error "Missing username in credential format"

echo ""
echo "  Line 1330: git clone --branch '\$repo_branch' '\$repo_url' '\$project_repo_path'"
log_error "Uses plain HTTPS URL instead of authenticated URL"

echo ""
log_info "Recommended fixes:"
echo "  1. Fix credential format to include username"
echo "  2. Use authenticated URL for git clone as fallback"
echo "  3. Add better error handling and retry logic"

echo ""
echo "🎯 DIAGNOSIS COMPLETE"
echo "====================="
log_error "PRIMARY ISSUE: Git credential helper format missing username component"
log_error "SECONDARY ISSUE: Plain HTTPS URL used without embedded authentication"
log_success "Both issues are fixable with credential format and URL updates"