alias.ps1

# 1. Core Function: Loads environment variables from a specified path
function Load-EnvironmentVariablesFromFile {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Path
    )

    if (-not (Test-Path -Path $Path -PathType Leaf)) {
        Write-Error "File not found: '$Path'"; return
    }

    $content = Get-Content -Path $Path | ForEach-Object { $_.Trim() }
    $regex = '^export\s+(?<Name>[a-zA-Z_][a-zA-Z0-9_]*)=(?<Value>.*)$'
    $varCount = 0
    Write-Host "--- Loading Environment Variables from '$Path' ---" -ForegroundColor Cyan

    # Define keywords for redaction (case-insensitive)
    $RedactKeywords = @('password', 'secret', 'key', 'token')

    foreach ($line in $content) {
        if ($line.StartsWith('#') -or [string]::IsNullOrWhiteSpace($line)) {
            continue
        }

        # Use the .NET [regex]::Match static method for reliable group access
        $match = [regex]::Match($line, $regex)

        if ($match.Success) {
            # Correctly extract named groups
            $name = $match.Groups['Name'].Value
            $value = $match.Groups['Value'].Value

            # Remove surrounding quotes
            if (($value.StartsWith('"') -and $value.EndsWith('"')) -or `
                ($value.StartsWith("'") -and $value.EndsWith("'"))) {
                $value = $value.Trim([char[]]"'").Trim([char[]]'"')
            }

            # -----------------------------------------------------------------
            # REDACTION LOGIC START
            # Check if the name contains any of the sensitive keywords
            $isSensitive = $false
            foreach ($keyword in $RedactKeywords) {
                if ($name -like "*$keyword*") {
                    $isSensitive = $true
                    break
                }
            }

            # Set the environment variable in the current session (always set the real value)
            Set-Item -Path "Env:$name" -Value $value -Force

            # Print the output to the console
            if ($isSensitive) {
                Write-Host "✅ Set: $name = [Redacted]" -ForegroundColor Yellow
            } else {
                Write-Host "✅ Set: $name = '$value'" -ForegroundColor Green
            }
            # REDACTION LOGIC END
            # -----------------------------------------------------------------

            $varCount++
        }
    }

    Write-Host "--- Successfully loaded $varCount environment variable(s). ---" -ForegroundColor Cyan
}

# 2. Wrapper Function/Alias: Enables 'source .env' like usage
function source {
    param(
        [Parameter(Mandatory=$true, Position=0)]
        [string]$File
    )

    Load-EnvironmentVariablesFromFile -Path $File
}