#!/bin/bash
# omarchy:summary=Create an AI profile binding a harness, provider, and model
# omarchy:args=<name> <harness> <provider> <model|default-coding|fast>
# omarchy:examples=omarchycn ai profile create work claude-code deepseek default-coding

set -euo pipefail

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

name="${1:?usage: omarchycn ai profile create <name> <harness> <provider> <model>}"
harness="${2:?missing harness}"
provider="${3:?missing provider}"
model="${4:?missing model}"

if [[ ! $name =~ ^[a-z0-9-]+$ ]]; then
  echo "Profile name must be lowercase alphanumeric/dashes: $name" >&2
  exit 1
fi

cn_ai_harness_field "$harness" command > /dev/null || {
  echo "Unknown harness: $harness (known: $(cn_ai_harness_ids | tr '\n' ' '))" >&2
  exit 1
}
jq -e --arg p "$provider" '.providers[$p]' "$CN_AI_PROVIDERS" > /dev/null || {
  echo "Unknown provider: $provider (known: $(cn_ai_provider_ids | tr '\n' ' '))" >&2
  exit 1
}

level=$(cn_ai_combo_level "$harness" "$provider")
if [[ $level == "unsupported" ]]; then
  echo "Combo $harness x $provider is not in the compatibility matrix" >&2
  exit 1
fi

allowlist=$(cn_ai_combo_models "$harness" "$provider")
if [[ -n $allowlist ]]; then
  # Combo-restricted model set (e.g. codex uses its own catalog slugs)
  if ! grep -qxF "$model" <<<"$allowlist"; then
    echo "Model $model not supported for $harness x $provider" >&2
    echo "Supported: $(tr '\n' ' ' <<<"$allowlist")" >&2
    exit 1
  fi
else
  resolved=$(cn_ai_model_by_alias "$provider" "$model" 2>/dev/null || true)
  if [[ -n $resolved ]]; then
    model="$resolved"
  elif ! cn_ai_models "$provider" | grep -qxF "$model"; then
    echo "Unknown model for $provider: $model" >&2
    echo "Available: $(cn_ai_models "$provider" | tr '\n' ' ')" >&2
    exit 1
  fi
  model_proto=$(cn_ai_model_protocol "$provider" "$model")
  harness_proto=$(cn_ai_harness_field "$harness" protocol)
  if [[ -n $model_proto && $model_proto != "$harness_proto" ]]; then
    echo "Model $model speaks $model_proto, but $harness needs $harness_proto" >&2
    exit 1
  fi
fi

mkdir -p "$CN_AI_PROFILE_DIR"
cat > "$CN_AI_PROFILE_DIR/$name.toml" <<EOF
schema_version = 1
name = "$name"
harness = "$harness"
provider = "$provider"
model = "$model"
secret_ref = "omarchycn://ai/$provider"
EOF

echo "Profile $name: $harness x $provider x $model (compat: $level)"
if ! omarchy-cn-ai-secret get "$provider" > /dev/null 2>&1; then
  echo "提示: 尚未存储 $provider 的 API Key，运行: omarchycn ai secret set $provider"
fi
