#!/usr/bin/env bash
# Azure Login Helper Script
# Helps authenticate with Azure CLI, especially for WSL users

set -euo pipefail


# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

# Load environment variables
if [ -f "${PROJECT_ROOT}/.env" ]; then
    set -a
    source "${PROJECT_ROOT}/.env"
    set +a
fi

# Logging function
log() {
    log_success "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}

error() {
    log_error "[ERROR] $1"
    exit 1
}

warn() {
    log_warn "[WARNING] $1"
}

info() {
    log_info "[INFO] $1"
}

# Check if Azure CLI is installed
check_azure_cli() {
    if ! command -v az &> /dev/null; then
        error "Azure CLI is not installed."
        error "
        error "Installation instructions:"
        error "  WSL/Ubuntu: curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash"
        error "  macOS: brew install azure-cli"
        error "  Windows: https://aka.ms/installazurecliwindows"
        error "
        error "See: https://docs.microsoft.com/cli/azure/install-azure-cli"
        exit 1
    fi
    
    log "Azure CLI is installed: $(az --version | head -n 1)"
}

# Check if already logged in
check_already_logged_in() {
    if az account show &> /dev/null; then
        local current_sub=$(az account show --query id -o tsv 2>/dev/null || echo "")
        local current_user=$(az account show --query user.name -o tsv 2>/dev/null || echo "")
        
        log "Already logged in to Azure"
        log "Current user: $current_user"
        log "Current subscription: $current_sub"
        
        # Check if subscription matches (if AZURE_SUBSCRIPTION_ID is set)
        if [ -n "${AZURE_SUBSCRIPTION_ID:-}" ] && [ "$current_sub" != "$AZURE_SUBSCRIPTION_ID" ]; then
            warn "Current subscription ($current_sub) does not match AZURE_SUBSCRIPTION_ID ($AZURE_SUBSCRIPTION_ID)"
            info "Setting subscription to: $AZURE_SUBSCRIPTION_ID"
            az account set --subscription "$AZURE_SUBSCRIPTION_ID" || error "Failed to set Azure subscription"
            log "Subscription set to: $AZURE_SUBSCRIPTION_ID"
        fi
        
        return 0
    fi
    
    return 1
}

# Login with interactive browser
login_interactive() {
    log "Logging in to Azure interactively..."
    info "This will open a browser window for authentication"
    
    az login || error "Azure login failed"
    
    # List available subscriptions
    log "Available subscriptions:"
    az account list --output table || error "Failed to list subscriptions"
    
    # Set subscription if AZURE_SUBSCRIPTION_ID is set
    if [ -n "${AZURE_SUBSCRIPTION_ID:-}" ]; then
        info "Setting subscription to: $AZURE_SUBSCRIPTION_ID"
        az account set --subscription "$AZURE_SUBSCRIPTION_ID" || error "Failed to set Azure subscription"
        log "Subscription set to: $AZURE_SUBSCRIPTION_ID"
    else
        warn "AZURE_SUBSCRIPTION_ID is not set. Using default subscription."
        info "To set a specific subscription, run: az account set --subscription <subscription-id>"
    fi
    
    # Verify login
    local current_sub=$(az account show --query id -o tsv 2>/dev/null || echo "")
    local current_user=$(az account show --query user.name -o tsv 2>/dev/null || echo "")
    
    log "Login successful"
    log "Current user: $current_user"
    log "Current subscription: $current_sub"
}

# Login with service principal
login_service_principal() {
    local app_id="${AZURE_CLIENT_ID:-}"
    local app_secret="${AZURE_CLIENT_SECRET:-}"
    local tenant_id="${AZURE_TENANT_ID:-}"
    
    if [ -z "$app_id" ] || [ -z "$app_secret" ] || [ -z "$tenant_id" ]; then
        error "Service principal credentials not found in environment variables"
        error "Required: AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID"
        exit 1
    fi
    
    log "Logging in with service principal..."
    info "App ID: $app_id"
    info "Tenant ID: $tenant_id"
    
    az login --service-principal \
        --username "$app_id" \
        --password "$app_secret" \
        --tenant "$tenant_id" || error "Service principal login failed"
    
    # Set subscription if AZURE_SUBSCRIPTION_ID is set
    if [ -n "${AZURE_SUBSCRIPTION_ID:-}" ]; then
        info "Setting subscription to: $AZURE_SUBSCRIPTION_ID"
        az account set --subscription "$AZURE_SUBSCRIPTION_ID" || error "Failed to set Azure subscription"
        log "Subscription set to: $AZURE_SUBSCRIPTION_ID"
    fi
    
    # Verify login
    local current_sub=$(az account show --query id -o tsv 2>/dev/null || echo "")
    log "Login successful"
    log "Current subscription: $current_sub"
}

# Login with managed identity (for Azure VM/Container)
login_managed_identity() {
    log "Logging in with managed identity..."
    
    az login --identity || error "Managed identity login failed"
    
    # Set subscription if AZURE_SUBSCRIPTION_ID is set
    if [ -n "${AZURE_SUBSCRIPTION_ID:-}" ]; then
        info "Setting subscription to: $AZURE_SUBSCRIPTION_ID"
        az account set --subscription "$AZURE_SUBSCRIPTION_ID" || error "Failed to set Azure subscription"
        log "Subscription set to: $AZURE_SUBSCRIPTION_ID"
    fi
    
    # Verify login
    local current_sub=$(az account show --query id -o tsv 2>/dev/null || echo "")
    log "Login successful"
    log "Current subscription: $current_sub"
}

# Main function
main() {
    log "Azure Login Helper"
    log "=================="
    
    # Check if Azure CLI is installed
    check_azure_cli
    
    # Check if already logged in
    if check_already_logged_in; then
        log "Already authenticated. No action needed."
        exit 0
    fi
    
    # Determine login method
    local login_method="${1:-interactive}"
    
    case "$login_method" in
        interactive)
            login_interactive
            ;;
        service-principal|sp)
            login_service_principal
            ;;
        managed-identity|mi)
            login_managed_identity
            ;;
        *)
            error "Unknown login method: $login_method"
            error "
            error "Usage: $0 [interactive|service-principal|managed-identity]"
            error "
            error "Login methods:"
            error "  interactive          - Interactive browser login (default)"
            error "  service-principal    - Login with service principal (requires AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID)"
            error "  managed-identity     - Login with managed identity (for Azure VM/Container)"
            exit 1
            ;;
    esac
    
    # Verify authentication
    log "Verifying authentication..."
    if az account show &> /dev/null; then
        log "Authentication verified successfully"
    else
        error "Authentication verification failed"
    fi
    
    # Display account information
    log "Account information:"
    az account show --output table || error "Failed to get account information"
}

# Run main function
main "$@"

