#!/usr/bin/env bash
# XenLook Companion — guided one-click entry (Linux/macOS/WSL)
# Usage: xenlook-companion-setup.sh [region_lane] [ollama_model]
# Example: xenlook-companion-setup.sh kr xenlook-4b-ko
set -euo pipefail

REGION="${1:-kr}"
MODEL="${2:-xenlook-4b-ko}"
BASE="https://on.xenlook.com/chat"
QS="companion=setup"
QS+="&region=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))" "$REGION")"
QS+="&model=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))" "$MODEL")"
# detect OS for wizard
OS="linux"
uname_s="$(uname -s 2>/dev/null || echo Linux)"
case "$uname_s" in
  Darwin*) OS="mac" ;;
  MINGW*|MSYS*|CYGWIN*) OS="windows" ;;
  *) OS="linux" ;;
esac
QS+="&os=$OS"
URL="${BASE}?${QS}"

echo "[xenlook-companion] region=$REGION model=$MODEL os=$OS"
echo "[xenlook-companion] Opening setup wizard: $URL"
if command -v xdg-open >/dev/null 2>&1; then
  xdg-open "$URL" >/dev/null 2>&1 || true
elif command -v open >/dev/null 2>&1; then
  open "$URL" || true
else
  echo "Open this URL in your browser: $URL"
fi

echo ""
echo "Next (guided · unsigned signed .msi/.dmg still pending certificates):"
echo "  1) Install Ollama: https://ollama.com/download"
echo "  2) ollama pull $MODEL"
echo "  3) Complete wizard in browser (already opened)"
if command -v ollama >/dev/null 2>&1; then
  echo "[xenlook-companion] ollama found — pulling $MODEL (may take a while)"
  ollama pull "$MODEL" || echo "[xenlook-companion] WARN: pull failed — retry after Ollama UI install"
else
  echo "[xenlook-companion] ollama not in PATH — install from https://ollama.com/download"
fi
