#!/bin/bash
# omarchy:summary=Map an AI profile onto Omarchy's default agent and hotkey
# omarchy:args=[profile]
# omarchy:examples=omarchycn ai default | omarchycn ai default work

set -euo pipefail

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

profile="${1:-$(cn_ai_current_profile)}"

if [[ ! -f $CN_AI_PROFILE_DIR/$profile.toml ]]; then
  echo "No such profile: $profile" >&2
  exit 1
fi

harness=$(cn_ai_profile_field "$profile" harness)
provider=$(cn_ai_profile_field "$profile" provider)
model=$(cn_ai_profile_field "$profile" model)

# Only harnesses whose provider config persists in their own files can back
# the upstream hotkey; opencode is session-env only, natives self-auth
case "$harness" in
claude-code) agent="claude" ;;
codex) agent="codex" ;;
*)
  echo "$harness 无法映射为上游默认 Agent；用 omarchycn ai launch $profile 启动" >&2
  exit 1
  ;;
esac

command=$(cn_ai_harness_field "$harness" command)
if omarchy-cmd-missing "$command"; then
  install=$(cn_ai_harness_field "$harness" install)
  echo "Installing $harness: $install"
  $install
fi

key=$(omarchy-cn-ai-secret get "$provider")

case "$harness" in
claude-code)
  # Persist provider env in Claude Code's own settings so the upstream
  # Super+Shift+Ctrl+A -> omarchy-agent path launches fully configured
  settings="$HOME/.claude/settings.json"
  mkdir -p "${settings%/*}"
  base=$(cn_ai_endpoint "$provider" anthropic)
  fast=$(cn_ai_fast_model "$provider")
  current="{}"
  if [[ -s $settings ]]; then
    current=$(cat "$settings")
    cp "$settings" "$settings.omarchycn-bak-$(date +%Y%m%d-%H%M%S)"
  fi
  # Key reaches jq via environment, never the argument list
  rm -f "$settings.omarchycn-new"
  (
    umask 077
    CN_AI_KEY="$key" jq --arg base "$base" --arg model "$model" --arg fast "$fast" \
      '.env = (.env // {}) + {
        ANTHROPIC_BASE_URL: $base,
        ANTHROPIC_AUTH_TOKEN: env.CN_AI_KEY,
        ANTHROPIC_API_KEY: env.CN_AI_KEY,
        ANTHROPIC_MODEL: $model,
        ANTHROPIC_DEFAULT_SONNET_MODEL: $model,
        ANTHROPIC_DEFAULT_OPUS_MODEL: $model,
        ANTHROPIC_DEFAULT_HAIKU_MODEL: $fast
      }' <<<"$current" > "$settings.omarchycn-new"
  )
  mv "$settings.omarchycn-new" "$settings"
  ;;
codex)
  cn_ai_render_codex_config "$provider" "$model" "$key"
  ;;
esac

agent_file="$HOME/.config/omarchy/defaults/agent"
mkdir -p "${agent_file%/*}"
printf '%s\n' "$agent" > "$agent_file"

echo "默认 Agent: $agent（$profile: $provider x $model）"
echo "快捷键 Super+Shift+Ctrl+A 或 'omarchy agent' 将以该配置启动"
