#!/bin/zsh
set -eu

[[ "$(uname -s)" == "Darwin" ]] || {
  print -u2 -- "ERROR: this installer is only for macOS"
  exit 1
}
[[ "${CONFIRMED_ONE_TIME_VALIDATION:-0}" == "1" ]] || {
  print -u2 -- "ERROR: run the patch once, pass strict config_load, and complete one real Codex request first"
  exit 1
}

script_path="${1:A}"
provider_id="${2:-openai_http}"
codex_home="${CODEX_HOME:-$HOME/.codex}"
template_path="${0:A:h}/com.example.codex-force-http-provider.plist"
destination="$HOME/Library/LaunchAgents/online.aixiaobai.codex-force-http-provider.plist"
launchctl_bin="${LAUNCHCTL_BIN:-/bin/launchctl}"
temp_plist="$(mktemp "$codex_home/launch-agent.force-http.XXXXXX.plist")"

cleanup() { [[ -f "$temp_plist" ]] && rm -f -- "$temp_plist" }
trap cleanup EXIT INT TERM

[[ "$provider_id" =~ ^[A-Za-z0-9_-]+$ ]] || {
  print -u2 -- "ERROR: invalid provider id"
  exit 1
}
[[ -x "$script_path" ]] || {
  print -u2 -- "ERROR: patch script is not executable: $script_path"
  exit 1
}
[[ -f "$template_path" ]] || {
  print -u2 -- "ERROR: plist template not found: $template_path"
  exit 1
}
[[ -x "$launchctl_bin" ]] || {
  print -u2 -- "ERROR: launchctl not executable: $launchctl_bin"
  exit 1
}

mkdir -p -- "$codex_home/log" "$HOME/Library/LaunchAgents"

cp -- "$template_path" "$temp_plist"
plutil -replace ProgramArguments.0 -string "$script_path" "$temp_plist"
plutil -replace ProgramArguments.1 -string "$provider_id" "$temp_plist"
plutil -replace StandardOutPath -string "$codex_home/log/force-http-provider.out.log" "$temp_plist"
plutil -replace StandardErrorPath -string "$codex_home/log/force-http-provider.err.log" "$temp_plist"
plutil -lint "$temp_plist" >/dev/null
mv -f -- "$temp_plist" "$destination"
temp_plist=""

domain="gui/$(id -u)"
"$launchctl_bin" bootout "$domain" "$destination" >/dev/null 2>&1 || true
"$launchctl_bin" bootstrap "$domain" "$destination"
"$launchctl_bin" kickstart -k "$domain/online.aixiaobai.codex-force-http-provider"

print -- "OK: LaunchAgent installed or updated: $destination"
print -- "Triggers: login and every 1800 seconds; no WatchPaths and no resident service"
