Functions/Ses/Sesio-Config.ps1

# Import utilities
. $PSScriptRoot\..\Util.ps1

function Sesio-Config {
     param (
        [Parameter(Position=0, Mandatory=$true)]
        [string]$Command,
        
        [Parameter(ValueFromRemainingArguments=$true)]
        $RemainingArgs
    )

    switch ($Command.ToLower()) {
        "add" {
            $params = @{}
            for ($i = 0; $i -lt $RemainingArgs.Count; $i += 2) {
                if ($i + 1 -lt $RemainingArgs.Count) {
                    $params[$RemainingArgs[$i].TrimStart('-')] = $RemainingArgs[$i + 1]
                }
            }
            Config-Add @params
        }
        "azure" {
            Config-Azure @RemainingArgs
        }
        "list" { Config-List @RemainingArgs }
        "env" { Config-Env @RemainingArgs }
        "help" { Config-Help }
        default { Write-Host "Unknown command: $Command" }
    }
}

function Config-Azure {
   
    # Check if azd is installed
    $azdInstalled = $null -ne (Get-Command azd -ErrorAction SilentlyContinue)

    if (-not $azdInstalled) {
        Write-Host "$warningColor[Warning]$resetColor Azure Developer CLI (azd) is not installed. Do you want to download and install it? (Y/N)"
        if ($downloadChoice -eq 'Y' -or $downloadChoice -eq 'y') {
            Write-Host "$infoColor[Info]$resetColor Downloading and installing Azure Developer CLI (azd)..."
            winget install Microsoft.AzureDeveloperCLI
            
            # Refresh the PATH
            $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")
            
            Write-Host "$infoColor[Info]$resetColor Azure Developer CLI (azd) has been installed."
        } else {
            Write-Host "$errorColor[Error]$resetColor Azure Developer CLI (azd) is required for this operation. Exiting."
            return
        }
    }

    # Verify azd installation
    try {
        $azdVersion = azd version
        Write-Host "[$infoColor`Info$resetColor] Azure Developer CLI (azd) version: $azdVersion"
    } catch {
        Write-Host "[$errorColor`Error$resetColor] Unable to verify Azure Developer CLI (azd) installation. Please install it manually and try again."
        return
    }

    # Login to Azure
    Write-Host "[$infoColor`Info$resetColor] Logging in to Azure..."
    azd auth login

    # Prompt user to select a subscription
    $subscriptionId = Read-Host "Enter the Subscription ID you want to use: "

    # Set the selected subscription
    azd account set --subscription $subscriptionId

    Write-Host "[$infoColor`Info$resetColor] Azure configuration completed successfully."

}

function Config-Add {
    Write-Host "Adding config"
}

function Config-List {
    Write-Host "Listing config"
}

function Config-Help {
    Write-Host "$infoColor Sesio Config Help $resetColor"
    Write-Host ""
    Write-Host "$infoColor Usage: Sesio config <command> [options]$resetColor"
    Write-Host "$infoColor Commands:$resetColor"
    Write-Host "$infoColor--------------------------------$resetColor"
    Write-Host "$errorColor[add]$resetColor - Add configuration"
    Write-Host "$errorColor[azure]$resetColor - Configure Azure settings"
    Write-Host "$errorColor[list]$resetColor - List configurations"
    Write-Host "$errorColor[env]$resetColor - Manage environment variables"
    Write-Host " $warningColor[set]$resetColor KEY VALUE - Set environment variable"
    Write-Host " $warningColor[get]$resetColor KEY - Get environment variable"
    Write-Host " $warningColor[list]$resetColor - List all environment variables"
    Write-Host "$errorColor[help]$resetColor - Show help for a command"
    Write-Host "$infoColor[--------------------------------]$resetColor"
}

function Config-Env {
    param (
        [Parameter(Position=0)]
        [string]$Action,
        
        [Parameter(Position=1)]
        [string]$Key,
        
        [Parameter(Position=2)]
        [string]$Value
    )

    # Update to use .sesio folder for .env file
    $sesioFolder = Join-Path $env:USERPROFILE ".sesio"
    $envFile = Join-Path $sesioFolder ".env"

    # Create .sesio folder if it doesn't exist
    if (-not (Test-Path $sesioFolder)) {
        New-Item -ItemType Directory -Path $sesioFolder -Force | Out-Null
    }

    switch ($Action.ToLower()) {
        "set" {
            if ([string]::IsNullOrEmpty($Key) -or [string]::IsNullOrEmpty($Value)) {
                Write-Warning "Usage: sesio config env set KEY VALUE"
                return
            }
            Set-EnvVariable -Key $Key -Value $Value -EnvFile $envFile
        }
        "get" {
            if ([string]::IsNullOrEmpty($Key)) {
                Write-Warning "Usage: sesio config env get KEY"
                return
            }
            Get-EnvVariable -Key $Key -EnvFile $envFile
        }
        "list" {
            List-EnvVariables -EnvFile $envFile
        }
        default {
            Write-Error "Unknown env command. Available commands: set, get, list"
        }
    }
}

function Set-EnvVariable {
    param ($Key, $Value, $EnvFile)
    
    if (-not (Test-Path $EnvFile)) {
        New-Item -Path $EnvFile -ItemType File
    }

    $content = Get-Content $EnvFile -ErrorAction SilentlyContinue
    $newLine = "$Key=$Value"
    $keyExists = $false

    if ($content) {
        $newContent = @()
        foreach ($line in $content) {
            if ($line -match "^$Key=") {
                $newContent += $newLine
                $keyExists = $true
            } else {
                $newContent += $line
            }
        }
        if (-not $keyExists) {
            $newContent += $newLine
        }
        $newContent | Set-Content $EnvFile
    } else {
        $newLine | Set-Content $EnvFile
    }
    Write-Info "Environment variable '$Key' has been set"
}

function Get-EnvVariable {
    param ($Key, $EnvFile)
    
    if (-not (Test-Path $EnvFile)) {
        Write-Warning "Environment file not found"
        return
    }

    $content = Get-Content $EnvFile
    foreach ($line in $content) {
        if ($line -match "^$Key=(.*)$") {
            Write-Host "$Key=$($matches[1])"
            return
        }
    }
    Write-Warning "Environment variable '$Key' not found"
}

function List-EnvVariables {
    param ($EnvFile)
    
    if (-not (Test-Path $EnvFile)) {
        Write-Warning "Environment file not found"
        return
    }

    # Define sensitive variables
    $sensitiveVars = @(
        'AZURE_SUBSCRIPTION_ID',
        'AZURE_TENANT_ID',
        'api_key',
        'secret_key',
        'pwsh-key'
        # Add more sensitive variables as needed
    )

    $content = Get-Content $EnvFile
    if ($content) {
        $cyan = "`e[36m"
        $yellow = "`e[33m"
        $reset = "`e[0m"
        $green = "`e[32m"
        
        Write-Host "${green}Environment Variables:${reset}"
        Write-Host "${green}------------------------${reset}"
        
        $envVars = @()
        foreach ($line in $content) {
            if ($line -match "^(.+?)=(.*)$") {
                $key = $matches[1]
                $value = $matches[2]
                
                # Mask sensitive values
                if ($sensitiveVars -contains $key) {
                    $value = "********"
                }
                
                $envVars += [PSCustomObject]@{
                    Key = $key
                    Value = $value
                }
            }
        }
        
        $envVars | Format-Table -Property @{
            Label = "Variable"
            Expression = { "$cyan$($_.Key)$reset" }
            Width = 30
        }, @{
            Label = "Value"
            Expression = { "$yellow$($_.Value)$reset" }
            Width = 50
        }
    } else {
        Write-Warning "No environment variables found"
    }
}

export-modulemember -function Sesio-Config