# PSReadline settings
Set-PSReadlineKeyHandler -Key ctrl+d -Function ViExit
Set-PSReadlineKeyHandler -Key ctrl+a -Function BeginningOfLine
Set-PSReadlineKeyHandler -Key ctrl+e -Function EndOfLine
Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete
Set-PSReadLineKeyHandler -Chord UpArrow -Function HistorySearchBackward
Set-PSReadLineOption -HistorySearchCursorMovesToEnd

# Prompt setup
Try {
    # oh-my-posh prompt
    oh-my-posh init pwsh --config "$HOME/.alen.omp.yaml" | Invoke-Expression
}
Catch {
    # simple prompt
    function prompt {
        $lec = $lastExitCode
        if (!$(Test-Path variable:lastExitCode) -or ($lec -eq 0)) {
           $error = 0
        } else {
           $error = 1
        }
        Write-Host ""
        Write-Host " $(hostname) " -NoNewline -ForegroundColor Black -BackgroundColor Yellow
        Write-Host " $(Convert-Path $(Get-Location)) " -NoNewline -ForegroundColor White -BackgroundColor Blue
        Write-Host "" -ForegroundColor White -BackgroundColor Black
        if ($error) {
            Write-Host "❯" -NoNewline -ForegroundColor Red
        } else {
            Write-Host "❯" -NoNewline -ForegroundColor Green
        }
        return " "
    }
}

# Auto-env, the lazy way
function Try-AutoVenv {
    param (
        [Parameter(Mandatory=$true)] [string]$Path
    )
    if (-Not $(Test-Path Env:VIRTUAL_ENV) -And $(Test-Path .\venv\Scripts\Activate.ps1 -PathType Leaf)) {
        .\venv\Scripts\Activate.ps1
    }
}

function Register-AutoVenv {
    param()
    if (-not (Test-Path function:\global:AutoVenvOrigPrompt)) {
        Copy-Item function:\prompt function:\global:AutoVenvOrigPrompt
        $global:AutoVenvPromptScriptBlock = {
            Try-AutoVenv $pwd
            AutoVenvOrigPrompt
        }
        Set-Content -Path function:\prompt -Value $global:AutoVenvPromptScriptBlock -Force
    }
}

Register-AutoVenv

# Some aliases
Set-Alias -Name g -Value git
Set-Alias -Name q -Value ipython
Set-Alias -Name which -Value Get-Command

# Has to run after any prompt mods, so run last
if (Get-Module -ListAvailable -Name ZLocation) {
    Import-Module ZLocation
    Set-Alias -Name j -Value Invoke-ZLocation
}

# Colourful ls and l
if (Get-Module -ListAvailable -Name Get-ChildItemColor) {
    Import-Module Get-ChildItemColor
    Set-Alias l Get-ChildItem -Option AllScope
    Set-Alias ls Get-ChildItemColorFormatWide -Option AllScope
} else {
    Set-Alias l Get-ChildItem -Option AllScope
    Set-Alias ls Get-ChildItem
}

# TODO: Brew
Try {
    $(/opt/homebrew/bin/brew shellenv) | Invoke-Expression
}
Catch {}