# shellcheck shell=bash
# lib-onboarding-state.sh — запись результата мастера на диск.
#
# Constructor Pattern: 1 файл = state-запись. UI — в ui.sh, парсеры — в registry.sh.
#
# Пишет:
#   ~/.claude/.onboarded                       — флаг прохождения
#   ~/.claude/config/onboarding.toml           — выбор lang/transport/provider/model
#   ~/.claude/config/user-model-override.toml  — для kei-model-router (HIGH аудит-1)
#   ~/.claude/secrets/.env                     — добавляет ключи провайдера (chmod 600)

ONBOARDED_FLAG="${ONBOARDED_FLAG:-$HOME/.claude/.onboarded}"
ONBOARDING_CONFIG="${ONBOARDING_CONFIG:-$HOME/.claude/config/onboarding.toml}"
SECRETS_ENV="${SECRETS_ENV:-$HOME/.claude/secrets/.env}"

onboarding_write_secrets() {
  [ "${#ONBOARDING_AUTH_ENV_KEYS[@]}" = "0" ] && return
  mkdir -p "$(dirname "$SECRETS_ENV")"
  touch "$SECRETS_ENV"; chmod 600 "$SECRETS_ENV"
  local i
  for i in "${!ONBOARDING_AUTH_ENV_KEYS[@]}"; do
    local k="${ONBOARDING_AUTH_ENV_KEYS[$i]}"
    local v="${ONBOARDING_AUTH_ENV_VALUES[$i]}"
    if grep -q "^${k}=" "$SECRETS_ENV" 2>/dev/null; then
      grep -v "^${k}=" "$SECRETS_ENV" > "$SECRETS_ENV.tmp"
      mv "$SECRETS_ENV.tmp" "$SECRETS_ENV"
    fi
    printf '%s=%s\n' "$k" "$v" >> "$SECRETS_ENV"
  done
  chmod 600 "$SECRETS_ENV"
}

onboarding_write_config() {
  mkdir -p "$(dirname "$ONBOARDING_CONFIG")"
  cat > "$ONBOARDING_CONFIG" <<EOF
# KeiSeiKit onboarding choices. Auto-generated by lib-onboarding.sh.
# Re-run wizard: rm ~/.claude/.onboarded && ./install.sh
language = "$ONBOARDING_LANG"
transport = "$ONBOARDING_TRANSPORT"
provider = "$ONBOARDING_PROVIDER"
default_model = "$ONBOARDING_MODEL"
stack_profile = "$ONBOARDING_STACK"
enabled_packs = "$ONBOARDING_PACKS"
EOF

  # Override для kei-model-router (HIGH аудит-1).
  # Приоритет: --pinned flag > этот файл > agent-profiles.toml default_model_ref.
  local override_path="$HOME/.claude/config/user-model-override.toml"
  cat > "$override_path" <<EOF
# User-tier model override. Auto-generated by onboarding wizard.
# Format: kei-model-router::Registry::load_user_override().
# Priority: --pinned flag > этот файл > agent-profiles.toml default_model_ref.
provider = "$ONBOARDING_PROVIDER"
model = "$ONBOARDING_MODEL"
transport = "$ONBOARDING_TRANSPORT"
EOF

  : > "$ONBOARDED_FLAG"
}
