$ErrorActionPreference = "Stop"

$BaseUrl = if ($env:FARAY_LARK_GATEWAY_URL) { $env:FARAY_LARK_GATEWAY_URL } else { "https://sso.faray.org/lark-gateway" }
$InstallDir = if ($env:FARAY_LARK_INSTALL_DIR) {
    $env:FARAY_LARK_INSTALL_DIR
} elseif ($env:LOCALAPPDATA) {
    Join-Path $env:LOCALAPPDATA "Faray\LarkGateway\bin"
} else {
    Join-Path $HOME "AppData\Local\Faray\LarkGateway\bin"
}
$ClientPath = Join-Path $InstallDir "faray-lark.py"
$CmdPath = Join-Path $InstallDir "faray-lark.cmd"

$PythonCommand = $null
$PythonArgs = @()
if (Get-Command py -ErrorAction SilentlyContinue) {
    $PythonCommand = "py"
    $PythonArgs = @("-3")
} elseif (Get-Command python -ErrorAction SilentlyContinue) {
    $PythonCommand = "python"
} else {
    throw "Python 3 is required to run faray-lark. Install Python 3, then rerun this command."
}

New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null
$ClientUrl = "$BaseUrl/client/faray-lark"
Invoke-WebRequest -Uri $ClientUrl -OutFile $ClientPath -UseBasicParsing
& $PythonCommand @PythonArgs -m py_compile $ClientPath

$WrapperPython = if ($PythonCommand -eq "py") { "py -3" } else { "python" }
$Wrapper = @"
@echo off
$WrapperPython "%~dp0faray-lark.py" %*
"@
Set-Content -Path $CmdPath -Value $Wrapper -Encoding ASCII

Write-Host "Installed faray-lark to $CmdPath"
Write-Host "Next:"
Write-Host "  & `"$CmdPath`" login"
Write-Host "Codex MCP command:"
Write-Host "  $CmdPath mcp"
