#!/usr/bin/env bash
# Plexum-kimi-provider installer (Phase v0.1).
#
# Builds + installs:
#   ~/.plexum/plugins/plexum-kimi-provider/plexum-kimi-provider-plugin
#   ~/.plexum/plugins/plexum-kimi-provider/manifest.json
#
# Operator then writes the per-profile config:
#   ~/.plexum/plugins/plexum-kimi-provider/config.json
#     {"api_key": "sk-kimi-..."}
#
# Re-runnable. Profile data + config.json are never touched.
#
# Flags:
#   --profile <p>    Override profile root (default ~/.plexum)
set -euo pipefail

REPO="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
PROFILE_DIR="${HOME}/.plexum"

while [[ $# -gt 0 ]]; do
    case "$1" in
        --profile) PROFILE_DIR="$2"; shift 2 ;;
        -h|--help) sed -n '2,/^set -euo/p' "$0" | sed -n '/^#/p' | sed 's/^# \{0,1\}//'; exit 0 ;;
        *) echo "unknown flag: $1" >&2; exit 2 ;;
    esac
done

log() { printf '\033[1;34m[kimi-install]\033[0m %s\n' "$*"; }
command -v go >/dev/null || { echo "go not found on PATH" >&2; exit 1; }

PLUGIN_DIR="${PROFILE_DIR}/plugins/plexum-kimi-provider"
mkdir -p "${PLUGIN_DIR}"

cd "${REPO}"
VERSION="$(git describe --tags --always 2>/dev/null || echo dev)"
LDFLAGS="-X main.Version=${VERSION}"
log "building plexum-kimi-provider-plugin (v=${VERSION})"
CGO_ENABLED=0 go build -ldflags="${LDFLAGS}" \
    -o "${PLUGIN_DIR}/plexum-kimi-provider-plugin" \
    ./cmd/plexum-kimi-provider-plugin

cat > "${PLUGIN_DIR}/manifest.json" <<'EOF'
{
  "name": "plexum-kimi-provider",
  "version": "0.1.0",
  "activation": "lazy",
  "executable": "plexum-kimi-provider-plugin",
  "contracts": {
    "provider": {
      "models": ["kimi-for-coding", "kimi-code", "k2p5"]
    }
  }
}
EOF

cat <<EOF

[kimi-install] done.
  plugin binary: ${PLUGIN_DIR}/plexum-kimi-provider-plugin
  manifest:      ${PLUGIN_DIR}/manifest.json
  models:        kimi-for-coding (+ legacy aliases: kimi-code, k2p5)
  endpoint:      https://api.kimi.com/coding/v1/messages

Next steps:
  1. Write API key:
       cat > ${PLUGIN_DIR}/config.json <<JSON
       {"api_key": "sk-kimi-..."}
       JSON
       chmod 600 ${PLUGIN_DIR}/config.json
  2. Allow plugin:
       Add "plexum-kimi-provider" to ${PROFILE_DIR}/plexum.json's
       .plugins.allow array
  3. Point an agent at Kimi:
       plexum agent-add --model kimi-for-coding <agent-id>
  4. systemctl --user restart plexum
EOF
