#!/bin/sh
set -eu

catalog_url="${1:-https://api.tianjinlinghang.com/docs/assets/auto-review-20261002/linghang-self-review-model-catalog.json}"
expected_sha256='344464b4bfdeff232850712d2ddd87417daa3f662df419f011c68bea8b50a028'
codex_dir="${2:-${CODEX_HOME:-${HOME}/.codex}}"
catalog_dir="${codex_dir}/model-catalogs"
catalog_path="${catalog_dir}/linghang-self-review-model-catalog.json"
config_path="${codex_dir}/config.toml"
timestamp="$(date '+%Y%m%d-%H%M%S')"
temp_path="$(mktemp -t linghang-model-catalog.XXXXXX)"
temp_config=''

cleanup() {
  rm -f "$temp_path"
  if [ -n "$temp_config" ]; then rm -f "$temp_config"; fi
}
trap cleanup EXIT HUP INT TERM

curl -fsSL "$catalog_url" -o "$temp_path"
if command -v shasum >/dev/null 2>&1; then
  actual_sha256="$(shasum -a 256 "$temp_path" | awk '{print $1}')"
else
  actual_sha256="$(sha256sum "$temp_path" | awk '{print $1}')"
fi
if [ "$actual_sha256" != "$expected_sha256" ]; then
  printf '模型目录校验失败。实际 SHA-256：%s\n' "$actual_sha256" >&2
  exit 1
fi

for slug in \
  gpt-6.1-sol gpt-6-astra gpt-6-astra-fast gpt-6-sol gpt-6 \
  gpt-5.6-sol gpt-5.6-sol-fast gpt-5.6-sol-openai-compact \
  gpt-5.6-terra gpt-5.6-terra-fast gpt-5.6-terra-openai-compact \
  gpt-5.6-luna gpt-5.6 gpt-5.5 gpt-5.5-fast gpt-5.5-openai-compact \
  gpt-5.4 gpt-5.4-mini gpt-5.3-codex-spark
do
  if ! grep -Fq "\"auto_review_model_override\": \"${slug}\"" "$temp_path"; then
    printf '模型目录缺少审批配置：%s\n' "$slug" >&2
    exit 1
  fi
done

mkdir -p "$catalog_dir"
if [ ! -f "$catalog_path" ] || ! cmp -s "$temp_path" "$catalog_path"; then
  if [ -f "$catalog_path" ]; then cp -p "$catalog_path" "${catalog_path}.backup-${timestamp}"; fi
  cp "$temp_path" "$catalog_path"
fi
temp_config="$(mktemp "${codex_dir}/config.toml.tmp.XXXXXX")"
case "$catalog_path" in *\"*|*\\*) printf 'Unsupported quote or backslash in config path.\n' >&2; exit 1;; esac
catalog_line="model_catalog_json = \"${catalog_path}\""
printf '%s\n\n' "$catalog_line" > "$temp_config"
if [ -f "$config_path" ]; then
  awk '
    BEGIN { in_section = 0; skip_blank = 0 }
    /^[[:space:]]*\[/ { in_section = 1 }
    !in_section && /^[[:space:]]*model_catalog_json[[:space:]]*=/ { skip_blank = 1; next }
    skip_blank && /^[[:space:]]*$/ { skip_blank = 0; next }
    { skip_blank = 0; print }
  ' "$config_path" >> "$temp_config"
fi
if [ ! -f "$config_path" ] || ! cmp -s "$temp_config" "$config_path"; then
  if [ -f "$config_path" ]; then cp -p "$config_path" "${config_path}.backup-${timestamp}"; fi
  mv "$temp_config" "$config_path"
else
  rm -f "$temp_config"
fi
temp_config=''

printf '\033[32m配置完成：自动审批会跟随当前主对话模型。\033[0m\n'
printf '模型目录：%s\n' "$catalog_path"
printf '配置文件：%s\n' "$config_path"
printf '\033[33m请完全退出 Codex（包括菜单栏进程），然后重新打开。\033[0m\n'
