#!/bin/bash
# omarchy:summary=Interactive wizard: pick harness, provider, model, store key, test
# omarchy:examples=omarchycn ai setup

set -euo pipefail

source "$OMARCHY_PATH/cn/lib/ai.sh"

if [[ ! -t 0 ]]; then
  echo "omarchycn ai setup 需要交互终端；非交互场景用 omarchycn ai profile create" >&2
  exit 1
fi

harness=$(cn_ai_harness_ids | gum choose --header "选择 Harness")

# Only combos whose adapter actually renders at launch
mapfile -t providers < <(jq -r --arg h "$harness" \
  '.combos[$h] | to_entries[] | select(.value.adapter) | .key' "$CN_AI_COMPAT")
if (( ${#providers[@]} == 0 )); then
  echo "兼容矩阵中没有 $harness 的可用 Provider 组合" >&2
  exit 1
fi
provider=$(printf '%s\n' "${providers[@]}" | gum choose --header "选择 Provider（兼容级别见 docs）")

harness_proto=$(cn_ai_harness_field "$harness" protocol)
allowlist=$(cn_ai_combo_models "$harness" "$provider")
if cn_ai_models_dynamic "$provider"; then
  base=$(cn_ai_endpoint "$provider" "$harness_proto")
  if [[ $provider == "ollama" ]]; then
    if omarchy-cmd-missing ollama; then
      gum confirm "Ollama 未安装，现在安装本地服务？" || exit 1
      if omarchy-cmd-present nvidia-smi; then
        ollama_pkg=ollama-cuda
      elif omarchy-cmd-present rocminfo; then
        ollama_pkg=ollama-rocm
      else
        ollama_pkg=ollama
      fi
      omarchy-pkg-add "$ollama_pkg"
    fi
    if ! curl -sf --connect-timeout 3 "$base/api/tags" > /dev/null; then
      sudo systemctl enable --now ollama
    fi
  fi
  models=$(curl -sf --connect-timeout 3 "$base/api/tags" | jq -r '.models[].name' || true)
  if [[ -z $models ]]; then
    echo "无法列出本地模型（服务未运行或尚未拉取）：先 ollama pull <模型>（如 qwen3-coder）再重试" >&2
    exit 1
  fi
  model=$(gum choose --header "选择本地模型" <<<"$models")
elif [[ -n $allowlist ]]; then
  model=$(gum choose --header "选择模型" <<<"$allowlist")
else
  # Hide models bound to a different wire protocol than the harness speaks
  model=$(jq -r --arg p "$provider" --arg hp "$harness_proto" \
    '.providers[$p].models[] | select((.protocol // $hp) == $hp) | .id' \
    "$CN_AI_PROVIDERS" | gum choose --header "选择模型")
fi

default_name="$harness-$provider"
name=$(gum input --header "Profile 名称" --value "$default_name")

proto=$(cn_ai_harness_field "$harness" protocol)
if [[ $proto == "native" ]]; then
  omarchy-cn-ai-profile-create "$name" "$harness" "$provider" "$model"
  omarchy-cn-ai-profile-use "$name"
  echo "$harness 自管鉴权：首次启动时在 CLI 内完成官方登录"
  if gum confirm "立即启动并完成官方登录？"; then
    exec omarchy-cn-ai-launch "$name"
  fi
  echo "完成。启动: omarchycn ai launch"
  exit 0
fi

if ! cn_ai_resolve_key "$provider" > /dev/null 2>&1; then
  key=$(gum input --password --header "$provider API Key（获取: $(jq -r --arg p "$provider" '.providers[$p].key_url' "$CN_AI_PROVIDERS")）")
  printf '%s' "$key" | omarchy-cn-ai-secret set "$provider"
fi

# Keep any existing profile intact until the new config proves itself
profile_file="$CN_AI_PROFILE_DIR/$name.toml"
if [[ -f $profile_file ]]; then
  cp "$profile_file" "$profile_file.omarchycn-prev"
fi

omarchy-cn-ai-profile-create "$name" "$harness" "$provider" "$model"

if gum confirm "运行连接测试？"; then
  if ! omarchy-cn-ai-test "$name"; then
    if [[ -f $profile_file.omarchycn-prev ]]; then
      mv "$profile_file.omarchycn-prev" "$profile_file"
      echo "测试未通过，已恢复原 Profile $name" >&2
    else
      rm -f "$profile_file"
      echo "测试未通过，Profile $name 未保留" >&2
    fi
    exit 1
  fi
fi

rm -f "$profile_file.omarchycn-prev"
omarchy-cn-ai-profile-use "$name"

if [[ $harness == "claude-code" || $harness == "codex" ]]; then
  if gum confirm "设为系统默认 Agent（Super+Shift+Ctrl+A）？"; then
    omarchy-cn-ai-default "$name"
  fi
fi
echo "完成。启动: omarchycn ai launch"
