#!/usr/bin/env bash
# TzamunCode installer (macOS / Linux).  Usage:
#   curl -fsSL https://code.tzamun.ai/install | bash
#
# Installs a single self-contained binary — no Bun, Node, Python, compiler,
# make, or node-gyp. Detect platform, download the matching binary, drop it on
# PATH, write config. (Windows: irm https://code.tzamun.ai/install.ps1 | iex)
set -euo pipefail

BASE="https://code.tzamun.ai"
BIN="${TZAMUNCODE_BIN:-$HOME/.local/bin}"
CFG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/tzamuncode"
CFG="$CFG_DIR/tzamuncode.json"

say(){ printf '\033[32m›\033[0m %s\n' "$*"; }
warn(){ printf '\033[33m!\033[0m %s\n' "$*"; }

# --- 1. Detect platform -----------------------------------------------------
os="$(uname -s)"; arch="$(uname -m)"
case "$os" in
  Linux)  o="linux";;
  Darwin) o="darwin";;
  *) echo "Unsupported OS: $os. TzamunCode needs Linux or macOS (Windows: $BASE/install.ps1)." >&2; exit 1;;
esac
case "$arch" in
  x86_64|amd64)  a="x64";;
  arm64|aarch64) a="arm64";;
  *) echo "Unsupported CPU: $arch" >&2; exit 1;;
esac
asset="tzamuncode-${o}-${a}"

# We currently ship linux-x64 + darwin-arm64 + darwin-x64. Guard the gap.
if [ "$o" = "linux" ] && [ "$a" = "arm64" ]; then
  echo "No linux-arm64 binary yet. Ping us, or run on x64 / WSL-x64." >&2; exit 1
fi

# --- 2. Download the binary -------------------------------------------------
mkdir -p "$BIN"
tmp="$BIN/.tzamuncode.download"
say "Downloading TzamunCode ($o-$a)…"
curl -fSL "$BASE/$asset" -o "$tmp" --progress-bar
chmod +x "$tmp"
# curl-downloaded files aren't Gatekeeper-quarantined, but strip it just in case.
[ "$o" = "darwin" ] && xattr -d com.apple.quarantine "$tmp" 2>/dev/null || true
mv -f "$tmp" "$BIN/tzamuncode"
say "Installed → $BIN/tzamuncode"

# --- 3. Config (never clobber an existing one) ------------------------------
if [ ! -f "$CFG" ]; then
  mkdir -p "$CFG_DIR"
  cat > "$CFG" <<'JSON'
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "tzamun": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "TzamunAI Gateway",
      "options": { "baseURL": "https://code.tzamun.ai/api/v1" },
      "models": {
        "ILM:Coder":  { "name": "ILM Coder (30B)", "limit": { "context": 163840, "output": 8192 } },
        "ILM:Pro":    { "name": "ILM Pro", "limit": { "context": 24576, "output": 8192 } },
        "ILM:Vision": { "name": "ILM Vision", "limit": { "context": 32768, "output": 8192 } }
      }
    }
  },
  "model": "tzamun/ILM:Coder",
  "small_model": "tzamun/ILM:Pro"
}
JSON
  chmod 600 "$CFG"
  say "Wrote config → $CFG"
else
  warn "Existing config kept → $CFG (not overwritten)"
fi

# --- 3b. Import an existing OpenCode setup (MCP servers + skills), if present -
OC_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/opencode"
if [ -d "$OC_DIR" ] && command -v python3 >/dev/null 2>&1; then
  OC="$OC_DIR" TC="$CFG_DIR" TCF="$CFG" python3 - <<'PY' || true
import json, os, pathlib, shutil
oc = pathlib.Path(os.environ["OC"]); tc = pathlib.Path(os.environ["TC"]); tcf = pathlib.Path(os.environ["TCF"])
try:
    src = oc/"skills"
    if src.is_dir():
        dst = tc/"skills"; dst.mkdir(parents=True, exist_ok=True)
        for it in src.iterdir():
            d = dst/it.name
            if d.exists(): continue
            try:
                real = it.resolve()
                if real.is_dir(): shutil.copytree(real, d)
                elif real.exists(): shutil.copy2(real, d)
            except Exception as e: print("  (skipped skill", it.name, "-", e, ")")
        print("  imported skills:", ", ".join(p.name for p in dst.iterdir()) or "(none)")
except Exception as e: print("  (skills import skipped:", e, ")")
try:
    ocf = next((oc/f for f in ["opencode.jsonc","opencode.json","config.json"] if (oc/f).exists()), None)
    def load(p):
        try: return json.loads(p.read_text())
        except Exception: return {}
    if ocf:
        o = load(ocf); t = load(tcf)
        if o.get("mcp"):
            t.setdefault("mcp", {})
            for k,v in o["mcp"].items(): t["mcp"].setdefault(k, v)
            tcf.write_text(json.dumps(t, indent=2))
            print("  imported MCP servers:", ", ".join(o["mcp"].keys()))
except Exception as e: print("  (mcp import skipped:", e, ")")
PY
  say "Imported existing OpenCode MCPs/skills (if any)"
fi

echo
say "TzamunCode installed."
case ":$PATH:" in
  *":$BIN:"*) ;;
  *) warn "Add this to your shell profile so 'tzamuncode' is on PATH:"; echo "      export PATH=\"$BIN:\$PATH\"";;
esac
echo
say "Sign in with your mobile number, then start:"
echo "      tzamuncode login"
echo "      tzamuncode"
echo
say "SSH/PuTTY tip: new line = Ctrl+J | copy = Shift+drag | paste = Shift+Insert"
echo "      Full terminal tips: https://code.tzamun.ai/terminal"
