#!/bin/sh
# Pasang Epithre CLI di Linux/macOS.
# Jalankan:  curl -fsSL https://docs.isonai.com/downloads/epithre-cli/pasang-epithre-cli.sh | sh
# API key TIDAK ada di skrip ini; ditanya saat jalan (atau set EPITHRE_API_KEY).

set -u
ASSET_URL="${EPITHRE_ASSET_URL:-https://docs.isonai.com/downloads/epithre-cli}"
API_BASE="https://api.epithre.com/v1"
EPI_ROOT="${XDG_DATA_HOME:-$HOME/.local/share}/epithre"
CLI="$EPI_ROOT/cli/epithre"
DATA_DIR="$HOME/.epithre"
BIN_DIR="$HOME/.local/bin"
STAMP=$(date +%Y%m%d_%H%M%S)

say()  { printf '%s\n' "$*"; }
step() { printf '\n== %s\n' "$*"; }
die()  { printf 'Gagal: %s\n' "$*" >&2; exit 1; }

# curl | sh = stdin milik pipa; tanya lewat terminal bila ada.
HAVE_TTY=0
if (exec </dev/tty) 2>/dev/null; then HAVE_TTY=1; fi

ask() {  # ask "pertanyaan" default
    if [ "$HAVE_TTY" -eq 1 ]; then
        printf '%s ' "$1" >/dev/tty
        IFS= read -r ans </dev/tty || ans=""
        [ -n "$ans" ] && { printf '%s' "$ans"; return; }
    fi
    printf '%s' "$2"
}

ask_secret() {
    [ "$HAVE_TTY" -eq 1 ] || return 0
    printf '%s ' "$1" >/dev/tty
    stty -echo </dev/tty 2>/dev/null
    IFS= read -r ans </dev/tty || ans=""
    stty echo </dev/tty 2>/dev/null
    printf '\n' >/dev/tty
    printf '%s' "$ans"
}

key_from_settings() {
    [ -f "$1" ] && sed -n 's/.*"EPITHRE_API_KEY"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$1" | head -n 1
}

say ""
say "  EPITHRE. CLI"

# --- 1. Prasyarat ---
step "1/5 Cek prasyarat"
for c in curl bash tar; do
    command -v "$c" >/dev/null 2>&1 || die "perintah '$c' tidak ada; pasang dulu lalu ulangi."
done
case "$(uname -s)" in
    Linux|Darwin) say "OK ($(uname -s) $(uname -m))" ;;
    *) die "sistem $(uname -s) belum didukung (Linux/macOS saja)." ;;
esac

# --- 2. Berkas Epithre CLI ---
step "2/5 Unduh Epithre CLI"
mkdir -p "$EPI_ROOT/cli" "$DATA_DIR" "$BIN_DIR" || die "tak bisa membuat folder."
curl -fsSL "$ASSET_URL/epithre.sh" -o "$CLI.new" || die "unduh launcher gagal."
chmod 755 "$CLI.new" && mv -f "$CLI.new" "$CLI"
for f in logo-large.txt logo-small.txt; do
    curl -fsSL "$ASSET_URL/$f" -o "$DATA_DIR/$f" || die "unduh $f gagal."
done
ln -sf "$CLI" "$BIN_DIR/epithre"
say "Perintah: $BIN_DIR/epithre"

# --- 3. Key + settings ---
step "3/5 Key Epithre"
SETTINGS="$DATA_DIR/settings.json"
KEY="${EPITHRE_API_KEY:-}"
if [ -z "$KEY" ]; then
    KEY=$(key_from_settings "$SETTINGS")
    if [ -n "$KEY" ]; then
        tail4=$(printf '%s' "$KEY" | tail -c 4)
        case "$(ask "Pakai key yang sudah ada (...$tail4)? [Y/n]" y)" in
            [Nn]*) KEY="" ;;
        esac
    fi
fi
[ -n "$KEY" ] || KEY=$(ask_secret "Tempel API key Epithre (esk_live_...):")
KEY=$(printf '%s' "$KEY" | tr -d '[:space:]')
[ -n "$KEY" ] || die "key kosong. Jalankan di terminal interaktif, atau set EPITHRE_API_KEY."
case "$KEY" in *[!A-Za-z0-9_-]*) die "format key tidak dikenali." ;; esac
if curl -fsS -m 20 -o /dev/null -H "Authorization: Bearer $KEY" "$API_BASE/models"; then
    say "Key diterima."
else
    say "Peringatan: key belum bisa dicek. Setelan tetap ditulis."
fi
[ -f "$SETTINGS" ] && cp "$SETTINGS" "$SETTINGS.bak-$STAMP"

umask 077
cat >"$SETTINGS" <<EOF
{
  "env": { "EPITHRE_API_KEY": "$KEY" },
  "modelProviders": {
    "openai": [
      {
        "id": "epithre-prme",
        "name": "Epithre PRME (coding, konteks 256K, teks saja)",
        "baseUrl": "$API_BASE",
        "envKey": "EPITHRE_API_KEY",
        "generationConfig": {
          "contextWindowSize": 262144,
          "timeout": 300000,
          "streamIdleTimeoutMs": 600000,
          "modalities": { "image": false, "video": false, "pdf": false }
        }
      },
      {
        "id": "epithre-omni",
        "name": "Epithre Omni (konteks 128K, bisa gambar)",
        "baseUrl": "$API_BASE",
        "envKey": "EPITHRE_API_KEY",
        "generationConfig": {
          "contextWindowSize": 131072,
          "timeout": 120000,
          "streamIdleTimeoutMs": 600000,
          "maxRetries": 2,
          "modalities": { "image": true, "video": false, "pdf": false }
        },
        "capabilities": { "reasoning": { "profile": "qwen-chat-template" } }
      },
      {
        "id": "epithre-lyt",
        "name": "Epithre LYT (cepat, konteks 32K, obrolan ringan)",
        "baseUrl": "$API_BASE",
        "envKey": "EPITHRE_API_KEY",
        "generationConfig": {
          "contextWindowSize": 32768,
          "timeout": 60000,
          "modalities": { "image": false, "video": false, "pdf": false }
        }
      }
    ]
  },
  "security": { "auth": { "selectedType": "openai" } },
  "ide": { "enabled": false, "hasSeenNudge": true },
  "model": { "name": "epithre-prme", "skipNextSpeakerCheck": false },
  "general": { "enableAutoUpdate": false, "gitCoAuthor": { "commit": false, "pr": false } },
  "review": { "attribution": false },
  "privacy": { "usageStatisticsEnabled": false },
  "memory": { "enableManagedAutoMemory": false, "enableManagedAutoDream": false },
  "context": { "fileName": ["EPITHRE.md"] },
  "ui": {
    "theme": "Epithre",
    "customThemes": {
      "Epithre": {
        "name": "Epithre",
        "type": "custom",
        "Background": "#0b1018",
        "Foreground": "#d6dbe3",
        "LightBlue": "#9cc0ea",
        "AccentBlue": "#6f9bd1",
        "AccentPurple": "#a9b8e8",
        "AccentCyan": "#8ccfd9",
        "AccentGreen": "#9fcf8a",
        "AccentYellow": "#e3c27a",
        "AccentRed": "#e07a7a",
        "AccentYellowDim": "#7d6a3f",
        "AccentRedDim": "#7d3f45",
        "DiffAdded": "#9fcf8a",
        "DiffRemoved": "#e07a7a",
        "Comment": "#6b7686",
        "Gray": "#3a4454",
        "GradientColors": ["#c9dbf2", "#5b7fb0"]
      }
    },
    "customAsciiArt": { "small": { "path": "logo-small.txt" }, "large": { "path": "logo-large.txt" } },
    "customBannerTitle": ">_ Epithre CLI",
    "customBannerSubtitle": "Epithre Platform",
    "hideTips": true,
    "hideWindowTitle": true,
    "brand": { "name": "Epithre CLI" }
  }
}
EOF
umask 022
say "Setelan tersimpan: $SETTINGS"

# --- 4. Mesin ---
step "4/5 Pasang mesin (sekali, 1-2 menit)"
"$CLI" update || die "mesin gagal terpasang. Log: $DATA_DIR/engine-install.log"
[ -x "$EPI_ROOT/engine/core/node/bin/node" ] || die "mesin tidak lengkap. Log: $DATA_DIR/engine-install.log"

# --- 5. PATH ---
step "5/5 Daftarkan perintah 'epithre'"
case ":$PATH:" in
    *":$BIN_DIR:"*) say "$BIN_DIR sudah ada di PATH." ;;
    *)
        case "$(basename "${SHELL:-sh}")" in
            zsh)  RC="$HOME/.zshrc" ;;
            bash) if [ "$(uname -s)" = Darwin ]; then RC="$HOME/.bash_profile"; else RC="$HOME/.bashrc"; fi ;;
            *)    RC="$HOME/.profile" ;;
        esac
        if grep -q '# epithre-cli' "$RC" 2>/dev/null; then
            say "PATH sudah terdaftar di $RC (berlaku di terminal baru)."
        else
            printf '\n# epithre-cli\nexport PATH="$HOME/.local/bin:$PATH"\n' >>"$RC"
            say "PATH ditambahkan di $RC (berlaku di terminal baru)."
        fi
        ;;
esac

say ""
say "Tes: siapa kamu?"
"$CLI" -p "Siapa kamu? Jawab satu kalimat." || say "Tes gagal; jalankan 'epithre doctor'."
say ""
"$CLI" doctor
say ""
say "Selesai. Buka terminal baru lalu ketik: epithre"
say "Perintah lain: epithre update | epithre doctor | di dalam: /model"
