#!/bin/zsh
set -u

provider_id="${1:-openai_http}"
codex_home="${CODEX_HOME:-$HOME/.codex}"
config_file="$codex_home/config.toml"
codex_bin="${CODEX_BIN:-$(command -v codex 2>/dev/null || true)}"
lock_dir="$codex_home/.force-http-provider.lock"
temp_file=""
backup_file=""

fail() {
  print -u2 -- "ERROR: $1"
  exit "${2:-1}"
}

cleanup() {
  [[ -n "$temp_file" && -f "$temp_file" ]] && rm -f -- "$temp_file"
  [[ -d "$lock_dir" ]] && rmdir -- "$lock_dir" 2>/dev/null || true
}
trap cleanup EXIT INT TERM

[[ "$provider_id" =~ ^[A-Za-z0-9_-]+$ ]] || fail "provider id must use only letters, digits, underscore, or hyphen"
[[ -d "$codex_home" ]] || fail "CODEX_HOME does not exist: $codex_home"
[[ -f "$config_file" ]] || fail "config.toml does not exist: $config_file"
[[ -n "$codex_bin" && -x "$codex_bin" ]] || fail "Codex executable not found; set CODEX_BIN to the real executable"

if ! mkdir -- "$lock_dir" 2>/dev/null; then
  fail "another provider patch is already running" 75
fi

read -r root_count table_count websocket_count <<EOF
$(awk -v provider="$provider_id" '
  BEGIN { root = 1; target = 0; roots = 0; tables = 0; websockets = 0 }
  {
    raw = $0
    compact = raw
    sub(/[[:space:]]+#.*/, "", compact)
    gsub(/[[:space:]]/, "", compact)
    if (compact ~ /^\[.*\]$/) {
      root = 0
      target = (compact == "[model_providers." provider "]")
      if (target) tables++
      next
    }
    if (root && raw ~ /^[[:space:]]*model_provider[[:space:]]*=/) roots++
    if (target && raw ~ /^[[:space:]]*supports_websockets[[:space:]]*=/) websockets++
  }
  END { print roots, tables, websockets }
' "$config_file")
EOF

[[ "$root_count" -le 1 ]] || fail "duplicate root model_provider keys; refusing to guess"
[[ "$table_count" -eq 1 ]] || fail "expected exactly one [model_providers.$provider_id] table; found $table_count"
[[ "$websocket_count" -le 1 ]] || fail "duplicate supports_websockets keys in target provider; refusing to guess"

temp_file="$(mktemp "$codex_home/config.toml.force-http.XXXXXX")" || fail "could not create temporary file"

awk -v provider="$provider_id" -v root_count="$root_count" -v websocket_count="$websocket_count" '
  BEGIN {
    root = 1
    target = 0
    inserted_ws = 0
    if (root_count == 0) print "model_provider = \"" provider "\""
  }
  {
    raw = $0
    compact = raw
    sub(/[[:space:]]+#.*/, "", compact)
    gsub(/[[:space:]]/, "", compact)
    is_table = (compact ~ /^\[.*\]$/)

    if (is_table) {
      if (target && websocket_count == 0 && !inserted_ws) {
        print "supports_websockets = false"
        inserted_ws = 1
      }
      root = 0
      target = (compact == "[model_providers." provider "]")
      print raw
      if (target && websocket_count == 0 && !inserted_ws) {
        print "supports_websockets = false"
        inserted_ws = 1
      }
      next
    }

    if (root && raw ~ /^[[:space:]]*model_provider[[:space:]]*=/) {
      comment = ""
      if (match(raw, /[[:space:]]+#.*/)) comment = substr(raw, RSTART)
      print "model_provider = \"" provider "\"" comment
      next
    }

    if (target && raw ~ /^[[:space:]]*supports_websockets[[:space:]]*=/) {
      comment = ""
      if (match(raw, /[[:space:]]+#.*/)) comment = substr(raw, RSTART)
      print "supports_websockets = false" comment
      next
    }

    print raw
  }
' "$config_file" > "$temp_file" || fail "could not build candidate config"

validate_config() {
  local doctor_file doctor_status
  doctor_file="$(mktemp "$codex_home/doctor.force-http.XXXXXX.json")" || return 1
  CODEX_HOME="$codex_home" "$codex_bin" --strict-config doctor --json > "$doctor_file" 2>/dev/null || true
  doctor_status="$(/usr/bin/osascript -l JavaScript - "$doctor_file" "$provider_id" <<'JXA'
function run(argv) {
  ObjC.import("Foundation");
  try {
    const data = $.NSData.dataWithContentsOfFile(argv[0]);
    const text = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding).js;
    const report = JSON.parse(text);
    const check = report.checks && report.checks["config.load"];
    if (!check || check.status !== "ok") return "FAIL: config.load did not pass";
    const active = check.details && check.details["model provider"];
    if (active !== argv[1]) return "FAIL: active provider is " + String(active);
    return "OK";
  } catch (error) {
    return "FAIL: doctor JSON could not be parsed (" + String(error) + ")";
  }
}
JXA
)"
  rm -f -- "$doctor_file"
  [[ "$doctor_status" == "OK" ]] || {
    print -u2 -- "$doctor_status"
    return 1
  }
}

if cmp -s -- "$config_file" "$temp_file"; then
  rm -f -- "$temp_file"
  temp_file=""
  validate_config || fail "existing config failed strict Codex validation; no file was changed"
  print -- "OK: already configured; no file changed"
  exit 0
fi

timestamp="$(date '+%Y%m%d-%H%M%S')"
backup_file="$codex_home/config.toml.before-http-$timestamp.bak"
if [[ -e "$backup_file" ]]; then
  backup_file="$codex_home/config.toml.before-http-$timestamp-$$.bak"
fi

cp -p -- "$config_file" "$backup_file" || fail "could not create timestamped backup"
chmod "$(stat -f '%Lp' "$config_file")" "$temp_file" || {
  cp -p -- "$backup_file" "$config_file"
  fail "could not preserve config permissions"
}
mv -f -- "$temp_file" "$config_file" || {
  cp -p -- "$backup_file" "$config_file"
  fail "could not replace config; backup restored"
}
temp_file=""

if ! validate_config; then
  cp -p -- "$backup_file" "$config_file"
  fail "strict config validation failed; backup restored"
fi

print -- "OK: config updated and strictly loaded by Codex"
print -- "Backup: $backup_file"
print -- "Next: run one real Codex request before installing any recurring trigger"
