# Initialize-AzureEnvironment.ps1
# This script ensures Azure PowerShell module is installed and authenticated
# Called by all other PowerShell scripts that require Az module

function Initialize-AzureEnvironment {
    [CmdletBinding()]
    param()
    
    Write-Host "Initializing Azure environment..." -ForegroundColor Cyan
    
    # Check if Az module is installed
    Write-Host "Checking for Azure PowerShell module (Az)..." -ForegroundColor Gray
    $azModule = Get-Module -ListAvailable -Name Az.Accounts -ErrorAction SilentlyContinue
    
    if (-not $azModule) {
        Write-Host "Azure PowerShell module (Az) not found." -ForegroundColor Yellow
        Write-Host "Installing Azure PowerShell module (Az.Accounts)..." -ForegroundColor Cyan
        
        try {
            # Install Az.Accounts module (core module, smaller footprint)
            Install-Module -Name Az.Accounts -Repository PSGallery -Force -AllowClobber -Scope CurrentUser -ErrorAction Stop
            Write-Host "✓ Az.Accounts module installed successfully." -ForegroundColor Green
            
            # Install additional required modules
            $requiredModules = @(
                'Az.Resources',
                'Az.OperationalInsights',
                'Az.Monitor',
                'Az.Network'
            )
            
            foreach ($moduleName in $requiredModules) {
                Write-Host "Installing $moduleName..." -ForegroundColor Gray
                Install-Module -Name $moduleName -Repository PSGallery -Force -AllowClobber -Scope CurrentUser -ErrorAction SilentlyContinue
            }
            
            Write-Host "✓ Required Azure modules installed." -ForegroundColor Green
        } catch {
            Write-Error "Failed to install Azure PowerShell module: $_"
            Write-Host "`nPlease install manually using:" -ForegroundColor Yellow
            Write-Host "  Install-Module -Name Az -Repository PSGallery -Force" -ForegroundColor Cyan
            exit 1
        }
    } else {
        Write-Host "✓ Azure PowerShell module found." -ForegroundColor Green
    }
    
    # Import the module
    Import-Module Az.Accounts -ErrorAction SilentlyContinue
    Import-Module Az.Resources -ErrorAction SilentlyContinue
    Import-Module Az.OperationalInsights -ErrorAction SilentlyContinue
    Import-Module Az.Monitor -ErrorAction SilentlyContinue
    Import-Module Az.Network -ErrorAction SilentlyContinue
    
    # Check if user is authenticated to Azure CLI
    Write-Host "Checking Azure CLI authentication..." -ForegroundColor Gray
    $cliAccount = az account show --output json 2>$null | ConvertFrom-Json
    
    if (-not $cliAccount) {
        Write-Host "Not authenticated to Azure CLI." -ForegroundColor Yellow
        Write-Host "Please run: az login" -ForegroundColor Cyan
        Write-Error "Azure CLI authentication required. Please run 'az login' and try again."
        exit 1
    }
    
    Write-Host "✓ Azure CLI authenticated." -ForegroundColor Green
    Write-Host "  Account: $($cliAccount.user.name)" -ForegroundColor Gray
    Write-Host "  Subscription: $($cliAccount.name)" -ForegroundColor Gray
    
    # Check if user is authenticated to Azure PowerShell
    Write-Host "Checking Azure PowerShell authentication..." -ForegroundColor Gray
    $context = Get-AzContext -ErrorAction SilentlyContinue
    
    if (-not $context) {
        Write-Host "Not authenticated to Azure PowerShell." -ForegroundColor Yellow
        Write-Host "Attempting to authenticate using Azure CLI credentials..." -ForegroundColor Cyan
        
        try {
            # Get access token from Azure CLI for ARM resource
            $accessToken = az account get-access-token --resource https://management.azure.com --query accessToken -o tsv 2>$null
            
            if ($accessToken) {
                # Connect using the token and tenant ID
                $tenantId = $cliAccount.tenantId
                Connect-AzAccount -AccessToken $accessToken -AccountId $cliAccount.user.name -TenantId $tenantId -ErrorAction SilentlyContinue | Out-Null
                
                # Set the subscription context
                Set-AzContext -Subscription $cliAccount.id -ErrorAction SilentlyContinue | Out-Null
                
                $context = Get-AzContext
                if ($context) {
                    Write-Host "✓ Successfully authenticated to Azure PowerShell using CLI credentials." -ForegroundColor Green
                } else {
                    throw "Failed to establish context"
                }
            } else {
                throw "Could not get access token from Azure CLI"
            }
        } catch {
            Write-Host "Could not authenticate using Azure CLI token." -ForegroundColor Yellow
            Write-Host "Attempting interactive login..." -ForegroundColor Cyan
            
            try {
                Connect-AzAccount -ErrorAction Stop | Out-Null
                $context = Get-AzContext
                Write-Host "✓ Successfully authenticated to Azure PowerShell." -ForegroundColor Green
            } catch {
                Write-Error "Failed to authenticate to Azure PowerShell. Please run 'Connect-AzAccount' manually."
                exit 1
            }
        }
    } else {
        Write-Host "✓ Already authenticated to Azure PowerShell." -ForegroundColor Green
        Write-Host "  Account: $($context.Account.Id)" -ForegroundColor Gray
        Write-Host "  Subscription: $($context.Subscription.Name)" -ForegroundColor Gray
    }
    
    Write-Host "" # Blank line for readability
    return $context
}

# Execute initialization
Initialize-AzureEnvironment
