#!/bin/bash
# omarchy:summary=Launch the AI harness configured by a profile
# omarchy:args=[profile]
# omarchy:examples=omarchycn ai launch | omarchycn ai launch 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)
command=$(cn_ai_harness_field "$harness" command)
config_method=$(cn_ai_harness_field "$harness" config_method)

if omarchy-cmd-missing "$command"; then
  install=$(cn_ai_harness_field "$harness" install)
  if [[ $install == doc:* ]]; then
    echo "$harness 未安装，安装方法见官方文档: ${install#doc:}" >&2
    exit 1
  fi
  echo "Installing $harness: $install"
  $install
fi

case "$config_method" in
env)
  key=$(cn_ai_resolve_key "$provider")
  if [[ $harness == "codex" ]]; then
    cn_ai_render_codex_config "$provider" "$model" "$key"
    exec "$command"
  fi
  env_exports=$(cn_ai_render_env "$harness" "$provider" "$model" "$key")
  eval "$env_exports"
  exec "$command"
  ;;
native)
  # Native harnesses (kimi-code, deep-code) manage their own auth
  exec "$command"
  ;;
*)
  echo "Unknown config method: $config_method" >&2
  exit 1
  ;;
esac
