# PowerShell profile for web-terminal to resemble Windows PowerShell

# Aliases
# Explicitly define opencode function to avoid "cd" wrapper issues from global scope
function opencode {
    & /usr/local/bin/opencode @args
}
Set-Alias oc opencode

# Model-specific aliases/shortcuts
function gemini {
    # Call the actual Gemini CLI if installed
    if (Get-Command gemini-cli -ErrorAction SilentlyContinue) {
        & gemini-cli @args
    } else {
        Write-Warning "Gemini CLI not found. Install it with 'npm install -g @google/gemini-cli' or use 'opencode --model gemini' if that model is available."
    }
}

function qwen {
    & /usr/local/bin/opencode --model qwen @args
}

# Common Windows-style aliases to make the shell familiar
Set-Alias dir Get-ChildItem
Set-Alias ls Get-ChildItem
Set-Alias cls Clear-Host
function ipconfig {
    if (Get-Command ip -ErrorAction SilentlyContinue) { ip addr show }
    elseif (Get-Command ifconfig -ErrorAction SilentlyContinue) { ifconfig }
    else { Write-Warning 'No ip or ifconfig command available inside the container' }
}

# Color/Readline settings (if PSReadLine is available)
try {
    if (Get-Module -ListAvailable -Name PSReadLine) {
        Import-Module PSReadLine -ErrorAction SilentlyContinue
        Set-PSReadLineOption -EditMode Windows
    }
} catch {
    # PSReadLine might not be available; ignore
}

# Helpful prompt information
Write-Host "Welcome to Web PowerShell with SST OpenCode (opencode)!" -ForegroundColor Cyan
Write-Host "Type 'opencode --version' or 'oc --version' to confirm OpenCode CLI is ready." -ForegroundColor Yellow

# Ensure default working directory is workspace if available
if (Test-Path -Path '/home/web/data') {
    try { Set-Location -Path '/home/web/data' } catch { }
}

# ==== GitHub helper functions ====
# Create ~/.netrc from token for HTTPS git authentication
function Set-GitHubNetrc {
    param(
        [Parameter(Mandatory=$false)] [string]$Token,
        [Parameter(Mandatory=$false)] [string]$Login = $env:GITHUB_USERNAME
    )

    if (-not $Token) {
        Write-Error "No token provided. Set the GITHUB_PAT environment variable or pass a Token to Set-GitHubNetrc."
        return
    }

    if (-not $Login) { $Login = 'x-access-token' }
    $netrcPath = "$HOME/.netrc"
    $content = "machine github.com login $Login password $Token`n"
    $content | Out-File -FilePath $netrcPath -Encoding ascii -Force

    # Attempt to set permissions on Unix-like systems
    try { chmod 600 $netrcPath } catch { }
    Write-Host "Wrote token to $netrcPath" -ForegroundColor Green
}

# Create netrc from env var or Docker secret file if available
function Ensure-GitHubNetrcFromEnvOrSecret {
    # If GITHUB_PAT env var is set, use it
    if ($env:GITHUB_PAT) {
        Set-GitHubNetrc -Token $env:GITHUB_PAT
        return
    }

    # If a token file is provided via env var (GITHUB_PAT_FILE) use that
    if ($env:GITHUB_PAT_FILE -and (Test-Path -Path $env:GITHUB_PAT_FILE)) {
        $token = Get-Content -Raw -Path $env:GITHUB_PAT_FILE
        Set-GitHubNetrc -Token $token
        return
    }

    # Common Docker secrets path
    if (Test-Path -Path '/run/secrets/GITHUB_PAT') {
        $token = Get-Content -Raw -Path '/run/secrets/GITHUB_PAT'
        Set-GitHubNetrc -Token $token
        return
    }

    # Nothing found, don't error — user might use SSH instead
}

# Call on profile load to wire up credentials automatically
Ensure-GitHubNetrcFromEnvOrSecret

# Helper wrapper for GitHub commands: pull, push, sync, clone, setconfig
function github {
    param(
        [Parameter(ValueFromRemainingArguments = $true)] [string[]]$Args
    )

    if (-not $Args -or $Args.Count -eq 0) { Write-Host "Usage: github <pull|push|sync|clone|setconfig> [options]"; return }

    $cmd = $Args[0]
    switch ($cmd) {
        'pull' { 
            if (-not (Get-Command git -ErrorAction SilentlyContinue)) { Write-Error "git is not available inside the container"; return }
            # Run a plain git pull per policy
            & git pull
        }
        'push' {
            if (-not (Get-Command git -ErrorAction SilentlyContinue)) { Write-Error "git is not available inside the container"; return }
            # Usage: github push [commit message]
            $msg = if ($Args.Count -gt 1) { $Args[1..($Args.Length - 1)] -join ' ' } else { "Update from web-terminal" }
            # Use git add . to match user preference and push explicitly to origin main
            & git add .; & git commit -m $msg; & git push origin main
        }
        'sync' {
            if (-not (Get-Command git -ErrorAction SilentlyContinue)) { Write-Error "git is not available inside the container"; return }
            # pull latest and push local commits
            & git pull; & git push origin main
        }
        'clone' {
            if ($Args.Count -lt 2) { Write-Error "Usage: github clone <repo-url> [target-folder]"; return }
            $url = $Args[1]
            # determine folder name from repo URL if not provided
            $dest = if ($Args.Count -gt 2) { $Args[2] } else {
                $m = [regex]::Match($url, '/?([^/]+?)(?:\.git)?$')
                if ($m.Success) { $m.Groups[1].Value } else { 'repo' }
            }
            & git clone $url $dest
        }
        'setconfig' {
            # github setconfig <user.name> <user.email>
            if ($Args.Count -lt 3) { Write-Error "Usage: github setconfig <user.name> <user.email>"; return }
            & git config --global user.name $Args[1]
            & git config --global user.email $Args[2]
            Write-Host "Git global config set: $($Args[1]) <$($Args[2])>" -ForegroundColor Green
        }
        default { 
            # Fallback to gh CLI if available, or to git
            if (Get-Command gh -ErrorAction SilentlyContinue) {
                & gh @Args
            } elseif (Get-Command git -ErrorAction SilentlyContinue) {
                & git @Args
            } else {
                Write-Error "No git or gh CLI found to run the requested command"
            }
        }
    }
}

Set-Alias github github

# End GitHub helpers
