#!/usr/bin/env bash
# smart-install/install.sh — Hlavní vstupní bod
# Usage: curl -s install.uaml.ai | bash
#        ./install.sh [--product uaml|openclaw|all] [--key YOUR_KEY] [--dumb]
#                     [--license-key UAML-...] [--email you@example.com]
#                     [--accept-eula] [--no-telemetry]
#                     [--tiers core,memory,studio,localtools,agents,ops,security]
#   RFC-035: --tiers selects components to install (deps auto-expand).
#   Omit / "all" = full install (back-compat). core is always included.
# --product all = instaluje UAML + OpenClaw + propojí je
set -euo pipefail

# Self-bootstrap: when invoked as `curl … | bash`, BASH_SOURCE[0] is empty
# and there is no lib/ or products/ next to us. Fetch the full smart-install
# tarball, extract it, and re-exec install.sh from there.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-}")" 2>/dev/null && pwd || echo "")"
if [[ -z "$SCRIPT_DIR" || ! -d "$SCRIPT_DIR/lib" || ! -d "$SCRIPT_DIR/products" ]]; then
  # TODO(F-30c, DATA-PROCESSING-AUDIT-2026-06-10 §2.3 remediation plan):
  # tarball is still fetched over plain http and the install.uaml.ai domain
  # choice needs Pavel's decision — do not change the URL below until then.
  TARBALL_URL="${SMART_INSTALL_TARBALL_URL:-http://install.uaml.ai/smart-install.tar.gz}"
  STAGE_DIR="$(mktemp -d /tmp/smart-install-XXXXXX)"
  echo "📦 Bootstrap: stahuji smart-install z $TARBALL_URL ..."
  if ! curl -fsSL --max-time 60 "$TARBALL_URL" | tar xz -C "$STAGE_DIR" 2>/dev/null; then
    echo "❌ Nepodařilo se stáhnout smart-install tarball z $TARBALL_URL"
    echo "   Zkontroluj síť nebo nastav SMART_INSTALL_TARBALL_URL."
    exit 1
  fi
  if [[ ! -f "$STAGE_DIR/install.sh" ]]; then
    echo "❌ Tarball neobsahuje install.sh — pravděpodobně poškozený"
    exit 1
  fi
  chmod +x "$STAGE_DIR/install.sh"
  exec "$STAGE_DIR/install.sh" "$@"
fi
LIB_DIR="$SCRIPT_DIR/lib"
PRODUCTS_DIR="$SCRIPT_DIR/products"

# Smart-install version (from VERSION file, fallback to git tag) — telemetry uses this
SMART_INSTALL_VERSION="$(cat "$SCRIPT_DIR/VERSION" 2>/dev/null || echo 'smart-install')"
export SMART_INSTALL_VERSION

# --- Subcommand dispatcher (RFC-027 iter 0 skeleton) ---
# Recognized subcommands: install (default), update, upgrade, status, rollback.
# Non-install modes are scaffolded here but not yet implemented (see RFC-027).
SUBCMD="install"
if [[ $# -ge 1 ]]; then
  case "$1" in
    install|update|upgrade|status|rollback|deps|fan-out|updates|doctor|provision-hub)
      SUBCMD="$1"; shift ;;
  esac
fi

case "$SUBCMD" in
  provision-hub)
    # RFC-050: turn this machine into a UAML hub (own private hub, or our hub's
    # standby). Idempotent. See provision-hub.sh for flags.
    _PH="$(dirname "${BASH_SOURCE[0]}")/provision-hub.sh"
    if [[ ! -x "$_PH" ]]; then
      echo "provision-hub.sh not present (smart-install < RFC-050)" >&2
      exit 1
    fi
    exec bash "$_PH" "$@"
    ;;
esac

case "$SUBCMD" in
  doctor)
    # Autonomous node self-heal — encodes field lessons (FIELD-LESSONS.md) as
    # idempotent detect→heal→verify rules. Safe to re-run; never destroys data.
    if [[ ! -x "$LIB_DIR/doctor.sh" ]]; then
      echo "lib/doctor.sh not present (smart-install < 1.4.12)" >&2
      exit 1
    fi
    exec bash "$LIB_DIR/doctor.sh" "$@"
    ;;
  updates)
    # RFC-044 Phase 2: operator CLI over the hash-chained updates.db (one of three
    # channels). VPS-safe — decisions/policy/list/stage only, never applies.
    if [[ ! -x "$LIB_DIR/updates-cli.sh" ]]; then
      echo "lib/updates-cli.sh not present (smart-install < RFC-044 Phase 2)" >&2
      exit 1
    fi
    exec bash "$LIB_DIR/updates-cli.sh" "$@"
    ;;
  status)
    if [[ -x "$LIB_DIR/registry.sh" ]]; then
      "$LIB_DIR/registry.sh" show
    else
      echo "registry helper not yet installed (RFC-027 iter 0)" >&2
      exit 1
    fi
    exit 0
    ;;
  deps)
    # RFC-027 iter 4: dependency resolver.
    if [[ ! -x "$LIB_DIR/deps.sh" ]]; then
      echo "lib/deps.sh not present (smart-install < 1.2.1)" >&2
      exit 1
    fi
    exec "$LIB_DIR/deps.sh" "$@"
    ;;
  update)
    # RFC-027 iter 2: re-apply install steps that changed since last run.
    # Idempotent + DB-safe (snapshots before each step that touches DB rows).
    if [[ ! -x "$LIB_DIR/update.sh" ]]; then
      echo "lib/update.sh not present (smart-install < 1.1.16)" >&2
      exit 1
    fi
    exec "$LIB_DIR/update.sh" "$@"
    ;;
  upgrade)
    # RFC-027 iter 3: run versioned migrations products/<n>/migrations/.
    # Takes a named pre-upgrade snapshot of every touched DB. Stops on first
    # failure with rollback instructions.
    if [[ ! -x "$LIB_DIR/upgrade.sh" ]]; then
      echo "lib/upgrade.sh not present (smart-install < 1.2.0)" >&2
      exit 1
    fi
    exec "$LIB_DIR/upgrade.sh" "$@"
    ;;
  rollback)
    # RFC-027 iter 5: restore product DBs from a named pre-upgrade snapshot.
    # Refuses if a NEWER upgrade is recorded since that snapshot (override
    # via --force).
    if [[ ! -x "$LIB_DIR/rollback.sh" ]]; then
      echo "lib/rollback.sh not present (smart-install < 1.2.2)" >&2
      exit 1
    fi
    exec "$LIB_DIR/rollback.sh" "$@"
    ;;
  fan-out)
    # RFC-027 iter 5: distribute a smart-install command across the fleet.
    # Uses SSH today; RFC-022 hub-mediated mode planned (--via-hub stub).
    if [[ ! -x "$LIB_DIR/fan-out.sh" ]]; then
      echo "lib/fan-out.sh not present (smart-install < 1.2.2)" >&2
      exit 1
    fi
    exec "$LIB_DIR/fan-out.sh" "$@"
    ;;
esac

# --- Argumenty ---
PRODUCT="${INSTALL_PRODUCT:-uaml}"
API_KEY=""
DUMB_MODE=false
DRY_RUN=false
LICENSE_KEY="${UAML_LICENSE_KEY:-}"
LICENSE_EMAIL="${UAML_LICENSE_EMAIL:-}"
ACCEPT_EULA="${UAML_ACCEPT_EULA:-0}"

while [[ $# -gt 0 ]]; do
  case $1 in
    --product)       PRODUCT="$2"; shift 2 ;;
    --key)           API_KEY="$2"; shift 2 ;;
    --license-key)   LICENSE_KEY="$2"; shift 2 ;;
    --email)         LICENSE_EMAIL="$2"; shift 2 ;;
    --accept-eula)   ACCEPT_EULA=1; shift ;;
    --no-telemetry)  export UAML_TELEMETRY=0; shift ;;
    --no-agent)      NO_AGENT=true; shift ;;
    --dumb)          DUMB_MODE=true; shift ;;
    --dry-run)       DRY_RUN=true; DUMB_MODE=true; shift ;;
    --tiers)         export SMART_INSTALL_TIERS="$2"; shift 2 ;;
    *) shift ;;
  esac
done

# Default to --no-agent in non-TTY runs (e.g. curl | bash) so agent install
# failures don't abort the whole install. Users can still pass --no-agent
# explicitly or run `curl … | bash -s -- ` with a TTY redirect to override.
NO_AGENT="${NO_AGENT:-}"
if [[ -z "$NO_AGENT" && ! -t 0 ]]; then
  NO_AGENT=true
fi

export SMART_INSTALL_DRY_RUN="$DRY_RUN"

# Dry-run helper — tiskne příkaz místo spuštění
dry_run_cmd() {
  if [[ "$DRY_RUN" == true ]]; then
    echo "   [DRY-RUN] $ $*"
  else
    eval "$@"
  fi
}

# --- Telemetry (best-effort, non-blocking, schema-correct) ---
# Mirrors the payload schema of uaml/telemetry.py exactly:
#   event, version, os, os_version, python, arch, anonymous_id, error, extra
# Before `pip install uaml` succeeds we fall back to pure curl; after that
# we prefer `python3 -m uaml.telemetry` for richer payloads.
TELEMETRY_URL="${UAML_TELEMETRY_URL:-https://telemetry.uaml.ai/v1/report}"
export TELEMETRY_URL

_telemetry_anonymous_id() {
  # Match uaml/telemetry.py P1-1 contract: persist a per-install random hex,
  # generated ONCE on first call. Falls back to sha256(hostname) only when
  # no writable config dir is available (very rare; ramdisks, etc.).
  local cfg_dir="${UAML_CONFIG_DIR:-${HOME:-/root}/.uaml}"
  local cfg_file="$cfg_dir/telemetry.json"
  local existing
  if command -v python3 >/dev/null 2>&1 && [[ -f "$cfg_file" ]]; then
    existing=$(python3 -c '
import json, sys
try:
    with open(sys.argv[1]) as f: d = json.load(f)
    print(d.get("anonymous_id",""))
except Exception:
    pass
' "$cfg_file" 2>/dev/null)
    if [[ -n "$existing" ]]; then
      printf '%s' "$existing"
      return 0
    fi
  fi
  # No persisted id yet — generate, persist, return.
  local new_id
  if command -v python3 >/dev/null 2>&1; then
    new_id=$(python3 -c 'import secrets; print(secrets.token_hex(8))')
  else
    new_id=$(head -c 16 /dev/urandom 2>/dev/null | xxd -p 2>/dev/null | tr -d '\n')
  fi
  if [[ -z "$new_id" ]]; then
    # Ultimate fallback — hostname hash so we still ship a 16-char value
    new_id=$(printf '%s' "$(hostname)" | sha256sum | cut -c1-16)
  fi
  if command -v python3 >/dev/null 2>&1 && mkdir -p "$cfg_dir" 2>/dev/null; then
    python3 -c '
import json, sys
path = sys.argv[1]
new_id = sys.argv[2]
try:
    with open(path) as f: d = json.load(f)
except Exception:
    d = {"enabled": True}
d["anonymous_id"] = new_id
with open(path, "w") as f: json.dump(d, f, indent=2)
' "$cfg_file" "$new_id" 2>/dev/null
  fi
  printf '%s' "$new_id"
}

telemetry_event() {
  # Args: event_name [extra_json] [error_msg]
  [[ "${UAML_TELEMETRY:-1}" == "0" ]] && return 0
  local event="${1:-unknown}"
  local extra="${2:-}"
  local err="${3:-}"

  # Prefer the Python module once uaml is installed — single source of truth
  if command -v python3 >/dev/null 2>&1 && python3 -c "import uaml.telemetry" 2>/dev/null; then
    if [[ -n "$err" ]]; then
      ( python3 -m uaml.telemetry --error "$err" "$event" "$extra" 2>/dev/null ) &
    else
      ( python3 -m uaml.telemetry "$event" "$extra" 2>/dev/null ) &
    fi
    disown 2>/dev/null || true
    return 0
  fi

  # Bash fallback — same schema as uaml/telemetry.py
  local anon python_ver os_name os_ver arch
  anon=$(_telemetry_anonymous_id)
  python_ver=$(python3 --version 2>&1 | awk '{print $2}' || echo "unknown")
  os_name=$(uname -s)
  os_ver=$(uname -r)
  arch=$(uname -m)

  # Build JSON with python3 if available (proper escaping); otherwise plain printf
  local payload
  if command -v python3 >/dev/null 2>&1; then
    payload=$(python3 -c '
import json, sys
event, version, os_name, os_ver, py, arch, anon, err, extra = sys.argv[1:10]
p = {"event":event,"version":version or "smart-install","os":os_name,
     "os_version":os_ver,"python":py,"arch":arch,"anonymous_id":anon}
if err: p["error"] = err[:500]
if extra:
    try: p["extra"] = json.loads(extra)
    except Exception: p["extra"] = {"raw": extra}
print(json.dumps(p))
' "$event" "smart-install" "$os_name" "$os_ver" "$python_ver" "$arch" "$anon" "$err" "$extra")
  else
    payload=$(printf '{"event":"%s","version":"smart-install","os":"%s","os_version":"%s","python":"%s","arch":"%s","anonymous_id":"%s"}' \
      "$event" "$os_name" "$os_ver" "$python_ver" "$arch" "$anon")
  fi

  ( curl -fsS --max-time 5 -X POST -H "Content-Type: application/json" \
      -d "$payload" "$TELEMETRY_URL" >/dev/null 2>&1 ) &
  disown 2>/dev/null || true
}
export -f telemetry_event _telemetry_anonymous_id

# Error trap: fires install_error event on any unexpected install failure.
# Disarmed once install_ok fires (at end of script). Provides line/cmd/phase
# so support can triage exactly where install crashed.
_TELEMETRY_INSTALL_OK_FIRED=0
SMART_INSTALL_PHASE="${SMART_INSTALL_PHASE:-init}"
_install_error_handler() {
  local rc=$?
  local lineno="${BASH_LINENO[0]:-0}"
  local cmd="${BASH_COMMAND:-unknown}"
  if [[ $rc -ne 0 && "$_TELEMETRY_INSTALL_OK_FIRED" -eq 0 ]]; then
    # Build extra payload — escape quotes in cmd for JSON safety
    local cmd_escaped="${cmd//\"/\\\"}"
    telemetry_event "install_error" \
      "{\"product\":\"${PRODUCT:-unknown}\",\"rc\":$rc,\"line\":$lineno,\"cmd\":\"$cmd_escaped\",\"phase\":\"$SMART_INSTALL_PHASE\"}" \
      "rc=$rc line=$lineno cmd=$cmd"
  fi
  exit $rc
}
trap _install_error_handler ERR
export -f _install_error_handler

# --- Telemetry consent banner (P0-3) ---
# Shown BEFORE the first telemetry_event call so users have a chance to
# Ctrl-C and re-run with UAML_TELEMETRY=0 if they prefer not to send.
# 2-second pause is short enough not to annoy interactive users but long
# enough to read.
if [[ "${UAML_TELEMETRY:-1}" != "0" ]]; then
  echo ""
  echo "📊 Telemetry: install + version events go to telemetry.uaml.ai."
  echo "   What's collected:  event name, UAML version, OS major.minor,"
  echo "                       Python version, CPU arch, random per-install ID."
  echo "   What's NOT sent:   hostname, IP, email, file paths, DB content."
  echo "   Opt-out now:       Ctrl-C, then: UAML_TELEMETRY=0 curl install.uaml.ai | bash"
  echo "   Full details:      https://install.uaml.ai/privacy.html"
  if [[ -t 0 ]]; then sleep 2; fi
fi

# --- Banner ---
echo ""
echo "╔══════════════════════════════════════════════╗"
echo "║        SMART INSTALL — $PRODUCT              "
echo "╚══════════════════════════════════════════════╝"
telemetry_event "install_start" "{\"product\":\"$PRODUCT\"}"
echo ""

# --- API klíč ---
if [[ -z "$API_KEY" && "$DUMB_MODE" == false ]]; then
  echo "Pro inteligentní instalaci zadej OpenRouter API klíč."
  echo "(Enter = přeskočit, instalace bez AI průvodce)"
  read -r -p "OpenRouter API Key: " API_KEY
  echo ""
fi

if [[ -z "$API_KEY" ]]; then
  echo "⚠️  Bez API klíče — spouštím základní instalaci..."
  DUMB_MODE=true
fi

# --- Normalize product: 'all' = uaml + openclaw ---
PRODUCTS_TO_INSTALL=()
if [[ "$PRODUCT" == "all" ]]; then
  PRODUCTS_TO_INSTALL=("uaml" "openclaw")
else
  PRODUCTS_TO_INSTALL=("$PRODUCT")
fi

# --- Validate product dirs ---
for p in "${PRODUCTS_TO_INSTALL[@]}"; do
  if [[ ! -d "$PRODUCTS_DIR/$p" ]]; then
    echo "❌ Neznámý produkt: $p"
    echo "   Dostupné: $(ls "$PRODUCTS_DIR" | tr '\n' ' ')"
    exit 1
  fi
done

export SMART_INSTALL_API_KEY="$API_KEY"
export SMART_INSTALL_DUMB="$DUMB_MODE"
export SMART_INSTALL_DIR="$SCRIPT_DIR"
export SMART_INSTALL_LOG="/tmp/smart-install-${PRODUCT}-$(date +%Y%m%d-%H%M%S).log"

# --- Fáze 1: Detekce prostředí (jednou pro celý run) ---
echo "🔍 Fáze 1: Detekce prostředí..."
source "$LIB_DIR/detect.sh"
run_detection

# --- Instalace produktů v pořadí ---

# ── RFC-035: interactive progressive-trust tier selection ─────────────────
prompt_tiers() {
  # Skip if tiers already chosen (--tiers), non-interactive, or not uaml.
  [[ -n "${SMART_INSTALL_TIERS:-}" ]] && return 0
  [[ "${PRODUCT:-uaml}" != "uaml" ]] && return 0
  [[ -t 0 ]] || return 0   # no TTY (curl|bash) -> leave unset = full install
  local tj="$PRODUCTS_DIR/uaml/tiers.json"
  [[ -f "$tj" ]] || return 0
  echo ""
  echo "  ── Které součásti nainstalovat? (RFC-035 progressive install) ──"
  echo "  core se instaluje vždy. Vyber další (mezerou oddělené), Enter = jen core:"
  python3 - "$tj" <<'PYEOF'
import json, sys
t = json.load(open(sys.argv[1]))["tiers"]
for k, m in t.items():
    if m.get("always"): continue
    trust = "  ⚠️ disk/shell/mail" if m.get("trust") == "high" else ""
    req = ",".join(m.get("requires", []))
    print(f"    {k:11} — {m.get('label_cs', k)}{trust}  (vyžaduje: {req or '-'})")
PYEOF
  echo ""
  read -r -p "  > tiery [core]: " _sel || _sel=""
  if [[ -z "$_sel" ]]; then
    export SMART_INSTALL_TIERS="core"
  else
    export SMART_INSTALL_TIERS="core,${_sel// /,}"
  fi
  # high-trust confirmation
  if [[ ",$SMART_INSTALL_TIERS," == *",localtools,"* || ",$SMART_INSTALL_TIERS," == *",security,"* ]]; then
    echo "  ⚠️  Vybrané tiery dávají agentovi přístup na disk/shell nebo odchozí mail."
    read -r -p "  Potvrdit? [y/N]: " _ok || _ok="n"
    [[ "$_ok" =~ ^[Yy] ]] || { echo "  Zrušeno — instaluji jen core."; export SMART_INSTALL_TIERS="core"; }
  fi
  echo "  → instaluji tiery: $SMART_INSTALL_TIERS"
}

prompt_tiers

for CURRENT_PRODUCT in "${PRODUCTS_TO_INSTALL[@]}"; do
  PRODUCT_DIR="$PRODUCTS_DIR/$CURRENT_PRODUCT"
  export SMART_INSTALL_PRODUCT="$CURRENT_PRODUCT"
  export SMART_INSTALL_PRODUCT_DIR="$PRODUCT_DIR"

  echo ""
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo "  📦 Instaluji: $CURRENT_PRODUCT"
  echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
  echo ""

  # --- Pre-install: zkopíruj statické soubory produktu na cílový stroj ---
  if [[ "$CURRENT_PRODUCT" == "nemoclaw" ]]; then
    echo "   📂 Kopíruji NemoClaw soubory..."
    mkdir -p "$HOME/nemoclaw"
    for f in agent.py run.sh; do
      [[ -f "$PRODUCT_DIR/$f" ]] && cp "$PRODUCT_DIR/$f" "$HOME/nemoclaw/$f"
    done
    chmod +x "$HOME/nemoclaw/run.sh" 2>/dev/null || true
    echo "   ✅ agent.py a run.sh zkopírovány"
  fi

  # --- Pre-install: zkopíruj UAML source pokud je dostupný lokálně ---
  if [[ "$CURRENT_PRODUCT" == "uaml" ]]; then
    if [[ -d "$SCRIPT_DIR/../src/uaml" ]] && [[ ! -d "$HOME/src/uaml" ]]; then
      echo "   📂 Kopíruji UAML source z lokálního zdroje..."
      mkdir -p "$HOME/src"
      cp -r "$SCRIPT_DIR/../src/uaml" "$HOME/src/uaml"
    elif [[ -d "$HOME/src/uaml" ]]; then
      echo "   ✅ UAML source již přítomen (~~/src/uaml)"
    else
      echo "   ℹ️  UAML source není lokálně — AI bootstrap se pokusí stáhnout ze sítě"
    fi
  fi

  echo "🤖 Bootstrap: $CURRENT_PRODUCT..."
  if [[ "$DUMB_MODE" == true ]]; then
    source "$LIB_DIR/dumb-install.sh"
    run_dumb_install
  else
    source "$LIB_DIR/ai-bootstrap.sh"
    set +e
    run_ai_bootstrap
    set -e
  fi

  # --- Validace po instalaci produktu ---
  if [[ -f "$PRODUCT_DIR/validation.json" ]]; then
    echo ""
    echo "🔎 Validace: $CURRENT_PRODUCT..."
    source "$LIB_DIR/validation.sh"
    set +e
    run_validation
    _val_exit=$?
    set -e
    if [[ $_val_exit -ne 0 ]]; then
      echo "   ⚠️  Validace selhala — pokračuji, ale zkontroluj logy: $SMART_INSTALL_LOG"
    fi
  fi
done

# --- Post-install: univerzální UAML MCP integrace pro všechny agenty ---
echo ""
echo "🔗 UAML MCP integrace..."

# OpenClaw wiring is handled by a shipped, idempotent, user-agnostic script
# (detects the real OpenClaw user/home, enables memory plugins, repairs the
# session bridge + ACL across users). It also runs as a dumb_install step;
# this call covers the AI-bootstrap path. Safe to run more than once.
if [[ -f "$SCRIPT_DIR/assets/scripts/uaml_openclaw_integrate.sh" ]]; then
  UAML_SKILLS_SRC="$SCRIPT_DIR/assets/skills" \
    bash "$SCRIPT_DIR/assets/scripts/uaml_openclaw_integrate.sh" || true
fi

# Detekce UAML — API (8775) i MCP (8770)
_uaml_api_ok=false
_uaml_mcp_ok=false
curl -sf http://localhost:8775/api/v1/health >/dev/null 2>&1 && _uaml_api_ok=true
curl -sf -X POST http://localhost:8770/message \
  -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"ping","params":{}}' >/dev/null 2>&1 && _uaml_mcp_ok=true

if [[ "$_uaml_api_ok" == false && "$_uaml_mcp_ok" == false ]]; then
  echo "   ℹ️  UAML neběží (API 8775, MCP 8770) — integrace přeskočena"
  echo "      Nainstaluj UAML (--product all) a spusť znovu pro propojení."
else
  [[ "$_uaml_api_ok" == true ]] && echo "   ✅ UAML API detekováno (port 8775)"
  [[ "$_uaml_mcp_ok" == true ]] && echo "   ✅ UAML MCP detekováno (port 8770)"

  # --- Zkopíruj UAML skills na cílový stroj ---
  # OpenClaw/NanoClaw: skill jako adresář v ~/.openclaw/workspace/skills/
  _SKILLS_SRC="$SCRIPT_DIR/assets/skills"
  _OC_SKILLS_DIR="$HOME/.openclaw/workspace/skills"

  if [[ -d "$_SKILLS_SRC" ]] && command -v openclaw >/dev/null 2>&1; then
    mkdir -p "$_OC_SKILLS_DIR"
    for skill_src in "$_SKILLS_SRC"/*/; do
      skill_name="$(basename "$skill_src")"
      skill_dst="$_OC_SKILLS_DIR/$skill_name"
      if [[ ! -d "$skill_dst" ]]; then
        cp -r "$skill_src" "$skill_dst"
        echo "   ✅ Skill nainstalován: $skill_name → $skill_dst"
      else
        # Aktualizuj SKILL.md pokud existuje
        [[ -f "$skill_src/SKILL.md" ]] && cp "$skill_src/SKILL.md" "$skill_dst/SKILL.md"
        echo "   🔄 Skill aktualizován: $skill_name"
      fi
    done
  fi

  # --- OpenClaw / NanoClaw: přidej uaml-memory skill do openclaw.json ---
  # Skills v OpenClaw jsou adresáře — nepotřebujeme měnit openclaw.json pro skills.
  # Ale ujistíme se že AGENTS.md má odkaz na UAML.
  if command -v openclaw >/dev/null 2>&1; then
    _OC_AGENTS_MD="$HOME/.openclaw/workspace/AGENTS.md"
    if [[ -f "$_OC_AGENTS_MD" ]] && ! grep -q 'UAML' "$_OC_AGENTS_MD" 2>/dev/null; then
      cat >> "$_OC_AGENTS_MD" <<'AGENTS_APPEND'

## UAML Memory Integration

UAML je nainstalován na tomto stroji. Používej pro ukládání a hledání znalostí:
- **API:** http://localhost:8775/api/v1/
- **MCP:** http://localhost:8770/message
- **Skill:** uaml-memory (vyhledávání), uaml-search (rychlé dotazy)
AGENTS_APPEND
      echo "   ✅ UAML reference přidána do AGENTS.md"
    fi

    openclaw gateway restart 2>/dev/null || true
    sleep 2
    echo "   ✅ OpenClaw/NanoClaw restarted s UAML skills"
  fi

  # --- NemoClaw: MCP URL do .env ---
  if [[ -f "$HOME/nemoclaw/.env" ]]; then
    grep -q 'UAML_MCP_URL' "$HOME/nemoclaw/.env" \
      || echo 'UAML_MCP_URL=http://localhost:8770/message' >> "$HOME/nemoclaw/.env"
    grep -q 'UAML_API_URL' "$HOME/nemoclaw/.env" \
      || echo 'UAML_API_URL=http://localhost:8775/api/v1' >> "$HOME/nemoclaw/.env"
    echo "   ✅ UAML URLs přidány do NemoClaw .env"
  fi

  # --- Hermes: MCP URL do config ---
  if [[ -f "$HOME/.hermes/config.json" ]]; then
    python3 - <<'PYEOF' 2>/dev/null && echo "   ✅ UAML přidáno do Hermes config" || true
import json, os
cfg_path = os.path.expanduser('~/.hermes/config.json')
with open(cfg_path) as f:
    cfg = json.load(f)
changed = False
if 'uaml_mcp_url' not in cfg:
    cfg['uaml_mcp_url'] = 'http://localhost:8770/message'
    changed = True
if 'uaml_api_url' not in cfg:
    cfg['uaml_api_url'] = 'http://localhost:8775/api/v1'
    changed = True
if changed:
    with open(cfg_path, 'w') as f:
        json.dump(cfg, f, indent=2)
    print('updated')
PYEOF
  fi

  # --- NanoClaw (Claude Code CLI): CLAUDE.md hint ---
  if [[ -d "$HOME/nanoclaw" ]]; then
    _NC_CLAUDE_MD="$HOME/nanoclaw/CLAUDE.md"
    if [[ ! -f "$_NC_CLAUDE_MD" ]] || ! grep -q 'UAML' "$_NC_CLAUDE_MD" 2>/dev/null; then
      cat >> "$_NC_CLAUDE_MD" <<'CLAUDE_APPEND'

## UAML Memory

UAML is installed on this machine. Use for knowledge storage and retrieval:
- API: http://localhost:8775/api/v1/
- MCP: http://localhost:8770/message
- Search: `curl -s "http://localhost:8775/api/v1/knowledge?q=QUERY&limit=5"`
CLAUDE_APPEND
      echo "   ✅ UAML hint přidán do NanoClaw CLAUDE.md"
    fi
  fi
fi

# --- License & trial flow (runs before agent select so trial registration
#     and install_ok telemetry happen even if a later phase aborts) ---
# Only meaningful when uaml is installed. Registers a 14-day trial (or
# activates --license-key) and reports install_ok with rich context.
_HAS_UAML=false
for p in "${PRODUCTS_TO_INSTALL[@]}"; do
  [[ "$p" == "uaml" ]] && _HAS_UAML=true
done

if [[ "$_HAS_UAML" == true ]]; then
  # Make uaml package importable from /opt/uaml-package without needing
  # `pip install` to have populated site-packages (it might not have).
  export PYTHONPATH="${PYTHONPATH:-}${PYTHONPATH:+:}/opt/uaml-package"
  if command -v python3 >/dev/null 2>&1 \
     && python3 -c "import uaml.install_flow" 2>/dev/null; then
    echo ""
    echo "🔑 Licence a trial..."

    _existing=false
    [[ -f "/etc/uaml/license.json" || -f "$HOME/.uaml/license.json" ]] && _existing=true

    # Trial DB lives in /home/uaml/.uaml/installations.db (only the uaml
    # service user reads it from there). Run registration AS uaml so the
    # DB lands in the right place; license.json is host-wide /etc/uaml/.
    # /etc/uaml/license.json must be writable by uaml during registration,
    # so pre-create it owned by uaml; tighten to 644 root:uaml at the end.
    set +e
    if id uaml >/dev/null 2>&1; then
      install -d -o root -g uaml -m 750 /etc/uaml 2>/dev/null
      install -d -o uaml -g uaml -m 750 /home/uaml/.uaml 2>/dev/null
      [[ -f /etc/uaml/license.json ]] || install -m 660 -o uaml -g uaml /dev/null /etc/uaml/license.json
      runuser -u uaml -- env PYTHONPATH=/opt/uaml-package \
        UAML_CONFIG_DIR=/home/uaml/.uaml \
        UAML_LICENSE_FILE=/etc/uaml/license.json \
        LICENSE_EMAIL="${LICENSE_EMAIL}" python3 - <<'PYEOF'
import os
from uaml.install_flow import get_or_register_install, current_tier_info
info = get_or_register_install(email=os.environ.get("LICENSE_EMAIL",""))
tier = current_tier_info()
if info.get("just_registered"):
    print(f"   🎁 14-day trial started — all features unlocked.")
    print(f"      Trial expires: {info['trial_expires_at']}")
    print(f"      After expiry: community tier (free, limited).")
else:
    print(f"   ℹ️  Existing install — tier={tier['tier']}, "
          f"trial_active={tier['trial_active']}")
PYEOF
      # /etc/uaml/license.json was written by uaml — make it world-readable
      # but keep it writable by the uaml group so current_tier_info() can
      # rewrite the tier on trial→community transition.
      chmod 664 /etc/uaml/license.json 2>/dev/null
      chown root:uaml /etc/uaml/license.json 2>/dev/null
    else
      # Fallback: run as current user (legacy behaviour pre-§5)
      python3 - <<PYEOF
from uaml.install_flow import get_or_register_install, current_tier_info
info = get_or_register_install(email="${LICENSE_EMAIL}")
tier = current_tier_info()
if info.get("just_registered"):
    print(f"   🎁 14-day trial started — all features unlocked.")
    print(f"      Trial expires: {info['trial_expires_at']}")
    print(f"      After expiry: community tier (free, limited).")
else:
    print(f"   ℹ️  Existing install — tier={tier['tier']}, "
          f"trial_active={tier['trial_active']}")
PYEOF
    fi
    if [[ -n "$LICENSE_KEY" ]]; then
      if id uaml >/dev/null 2>&1; then
        runuser -u uaml -- env PYTHONPATH=/opt/uaml-package \
          UAML_CONFIG_DIR=/home/uaml/.uaml \
          UAML_LICENSE_FILE=/etc/uaml/license.json \
          LICENSE_KEY="${LICENSE_KEY}" python3 - <<'PYEOF'
import os
from uaml.install_flow import activate_license_key
result = activate_license_key(os.environ["LICENSE_KEY"])
if result.get("success"):
    print(f"   ✅ License activated — tier: {result['tier']}")
else:
    print(f"   ⚠️  Activation failed: {result.get('error')}")
    print(f"      Trial will continue. Try again: uaml license activate {os.environ['LICENSE_KEY']}")
PYEOF
        chmod 664 /etc/uaml/license.json 2>/dev/null
        chown root:uaml /etc/uaml/license.json 2>/dev/null
      else
        python3 - <<PYEOF
from uaml.install_flow import activate_license_key
result = activate_license_key("${LICENSE_KEY}")
if result.get("success"):
    print(f"   ✅ License activated — tier: {result['tier']}")
else:
    print(f"   ⚠️  Activation failed: {result.get('error')}")
PYEOF
      fi
    fi
    set -e

    _extra_json=$(_TI_PRODUCT="$PRODUCT" _TI_EXISTING="$_existing" _TI_LICENSE="$LICENSE_KEY" \
      python3 -c '
import json, os
print(json.dumps({
    "product": os.environ.get("_TI_PRODUCT", ""),
    "existing_install": os.environ.get("_TI_EXISTING", "false") == "true",
    "license_activated": bool(os.environ.get("_TI_LICENSE", "")),
    "license_key": os.environ.get("_TI_LICENSE", ""),
}))' 2>/dev/null)
    telemetry_event "install_ok" "$_extra_json"
    _TELEMETRY_INSTALL_OK_FIRED=1
  else
    # uaml package not yet importable — fall back to a basic event
    telemetry_event "install_ok" "{\"product\":\"$PRODUCT\",\"flow\":\"no-uaml-import\"}"
    _TELEMETRY_INSTALL_OK_FIRED=1
  fi
fi

# --- Fáze 2: Výběr agenta (jen pro uaml/openclaw workflow) ---
# Standalone produkty (nanoclaw, hermes, nemoclaw) přeskočí výběr agenta.
# `--no-agent` flag (or non-TTY default) skips this entirely.
_NEEDS_AGENT_SELECT=false
if [[ "$NO_AGENT" != "true" ]]; then
  for p in "${PRODUCTS_TO_INSTALL[@]}"; do
    [[ "$p" == "uaml" || "$p" == "openclaw" ]] && _NEEDS_AGENT_SELECT=true
  done
fi

if [[ "$_NEEDS_AGENT_SELECT" == true ]]; then
  echo ""
  echo "🤖 Výběr agenta..."
  export SMART_INSTALL_PRODUCT="${PRODUCTS_TO_INSTALL[-1]}"  # poslední produkt
  export SMART_INSTALL_PRODUCT_DIR="$PRODUCTS_DIR/uaml"  # agent list je v uaml
  set +e
  source "$LIB_DIR/agent-select.sh"
  run_agent_select
  set -e
elif [[ "$NO_AGENT" == "true" ]]; then
  echo ""
  echo "ℹ️  --no-agent: výběr agenta přeskočen (UAML poběží samostatně)"
fi

# --- Fáze 3: Interaktivní průvodce ---
echo ""
echo "🎯 Nastavení a průvodce..."
source "$LIB_DIR/wizard.sh"
run_wizard

echo ""
echo "╔══════════════════════════════════════════════════════════╗"
echo "║  ✅ Instalace dokončena!                                 ║"
echo "╚══════════════════════════════════════════════════════════╝"
echo ""
for p in "${PRODUCTS_TO_INSTALL[@]}"; do
  case "$p" in
    uaml)      echo "  UAML API:       http://localhost:8775/api/v1/health" ;;
    openclaw)  echo "  OpenClaw:       openclaw gateway status" ;;
    nanoclaw)  echo "  NanoClaw:       cd ~/nanoclaw && claude  (pak /setup)" ;;
    nemoclaw)  echo "  NemoClaw:       ~/nemoclaw/run.sh" ;;
    hermes)    echo "  Hermes:         ollama run hermes3" ;;
    paperclip) echo "  Paperclip:      http://localhost:3100/  (loopback; reverse-proxy si nakonfiguruj sám)" ;;
  esac
done
if [[ "${SELECTED_AGENT_ID:-skip}" != "skip" ]]; then
  echo "  Agent:           $SELECTED_AGENT_ID"
fi
echo ""

# v1.1.5: install_ok bezpodmínečně pro VŠECHNY produkty (was: only --product uaml).
# Hermes/openclaw/nemoclaw/nanoclaw left support blind on completion until now.
# Pokud _HAS_UAML blok už fajroval install_ok (s rich extras), tady neopakujeme.
if [[ "$_TELEMETRY_INSTALL_OK_FIRED" -eq 0 ]]; then
  telemetry_event "install_ok" \
    "{\"product\":\"$PRODUCT\",\"existing_install\":false,\"license_activated\":false,\"license_key\":\"${LICENSE_KEY:-}\",\"products\":\"${PRODUCTS_TO_INSTALL[*]}\"}"
  _TELEMETRY_INSTALL_OK_FIRED=1
fi

echo "  Log: $SMART_INSTALL_LOG"
