#!/usr/bin/env bash
#
# OpenMac Installer
# Installiert OpenClaw + alles was für iOS/macOS-App-Entwicklung mit einem
# AI-Agenten nötig ist: Homebrew, Node.js, Xcode Command Line Tools, OpenClaw.
#
# Nutzung:
#   curl -fsSL https://openmac.psychologelinz.at/install.sh | bash
#
set -euo pipefail

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

BOLD="$(tput bold 2>/dev/null || true)"
RESET="$(tput sgr0 2>/dev/null || true)"
GREEN="$(tput setaf 2 2>/dev/null || true)"
YELLOW="$(tput setaf 3 2>/dev/null || true)"
RED="$(tput setaf 1 2>/dev/null || true)"
BLUE="$(tput setaf 4 2>/dev/null || true)"

info()  { printf "%s[OpenMac]%s %s\n" "$BLUE" "$RESET" "$1"; }
ok()    { printf "%s[OpenMac]%s %s\n" "$GREEN" "$RESET" "$1"; }
warn()  { printf "%s[OpenMac]%s %s\n" "$YELLOW" "$RESET" "$1"; }
fail()  { printf "%s[OpenMac]%s %s\n" "$RED" "$RESET" "$1"; exit 1; }

trap 'fail "Ein Schritt ist fehlgeschlagen (Zeile $LINENO). Installation abgebrochen."' ERR

# ---------------------------------------------------------------------------
# 1. macOS check
# ---------------------------------------------------------------------------

if [[ "$(uname -s)" != "Darwin" ]]; then
  fail "Dieses Script ist nur für macOS gedacht. Erkanntes System: $(uname -s)"
fi

macos_version="$(sw_vers -productVersion)"
macos_major="$(echo "$macos_version" | cut -d. -f1)"

info "macOS-Version erkannt: $macos_version"
if [[ "$macos_major" -lt 13 ]]; then
  warn "macOS $macos_version ist älter als die empfohlene Mindestversion (13 Ventura)."
  warn "Die Installation läuft trotzdem weiter, aber es kann zu Problemen kommen."
else
  ok "macOS-Version ist geeignet (>= 13 Ventura)."
fi

# ---------------------------------------------------------------------------
# 2. Xcode Command Line Tools
# ---------------------------------------------------------------------------

info "Prüfe Xcode Command Line Tools..."
if xcode-select -p >/dev/null 2>&1; then
  ok "Xcode Command Line Tools sind bereits installiert."
else
  warn "Xcode Command Line Tools fehlen. Starte Installation..."
  xcode-select --install || true
  echo ""
  echo "  ${BOLD}Es öffnet sich gleich ein System-Dialog.${RESET}"
  echo "  Bitte klicke dort auf 'Installieren' und warte, bis der Download fertig ist."
  echo "  Drücke danach hier Enter, um fortzufahren."
  echo ""
  read -r -p "  Weiter mit Enter, sobald die CLT-Installation abgeschlossen ist... " _ || true

  # Re-check after user confirms
  if ! xcode-select -p >/dev/null 2>&1; then
    fail "Xcode Command Line Tools sind immer noch nicht installiert. Bitte 'xcode-select --install' manuell abschließen und das Script erneut starten."
  fi
  ok "Xcode Command Line Tools installiert."
fi

# ---------------------------------------------------------------------------
# 3. Homebrew
# ---------------------------------------------------------------------------

info "Prüfe Homebrew..."
if command -v brew >/dev/null 2>&1; then
  ok "Homebrew ist bereits installiert ($(brew --version | head -n1))."
else
  warn "Homebrew fehlt. Installiere Homebrew (offizieller Weg)..."
  NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

  # Homebrew installs to different paths on Apple Silicon vs Intel
  if [[ -x /opt/homebrew/bin/brew ]]; then
    eval "$(/opt/homebrew/bin/brew shellenv)"
  elif [[ -x /usr/local/bin/brew ]]; then
    eval "$(/usr/local/bin/brew shellenv)"
  fi

  if ! command -v brew >/dev/null 2>&1; then
    fail "Homebrew-Installation ist fehlgeschlagen oder 'brew' nicht im PATH."
  fi
  ok "Homebrew installiert."
fi

# Make sure brew shellenv is active in this shell (idempotent, safe to re-run)
if [[ -x /opt/homebrew/bin/brew ]]; then
  eval "$(/opt/homebrew/bin/brew shellenv)"
elif [[ -x /usr/local/bin/brew ]]; then
  eval "$(/usr/local/bin/brew shellenv)"
fi

# Persist brew shellenv in shell profile if not already present
BREW_PREFIX="$(brew --prefix)"
SHELL_PROFILE="$HOME/.zprofile"
[[ "$SHELL" == *bash* ]] && SHELL_PROFILE="$HOME/.bash_profile"
if ! grep -qs "brew shellenv" "$SHELL_PROFILE" 2>/dev/null; then
  echo "eval \"\$(${BREW_PREFIX}/bin/brew shellenv)\"" >> "$SHELL_PROFILE"
  info "Homebrew-Umgebung zu $SHELL_PROFILE hinzugefügt."
fi

# ---------------------------------------------------------------------------
# 4. Node.js (LTS) via Homebrew
# ---------------------------------------------------------------------------

info "Prüfe Node.js..."
if command -v node >/dev/null 2>&1; then
  node_version="$(node --version)"
  ok "Node.js ist bereits installiert ($node_version)."
else
  info "Installiere Node.js LTS via Homebrew..."
  brew install node
  ok "Node.js installiert ($(node --version))."
fi

# ---------------------------------------------------------------------------
# 5. OpenClaw installieren
# ---------------------------------------------------------------------------
#
# Wir nutzen den offiziellen OpenClaw-Installer, der Node/Git-Setup,
# npm-Install und optionales Onboarding selbst übernimmt. Er ist idempotent
# und daher sicher mehrfach ausführbar.

# npm-Prefix auf benutzer-eigenes Verzeichnis setzen, damit kein sudo/root
# benötigt wird (Problem tritt auf, wenn Node nicht via Homebrew installiert wurde).
NPM_GLOBAL="$HOME/.npm-global"
mkdir -p "$NPM_GLOBAL"
npm config set prefix "$NPM_GLOBAL"
export PATH="$NPM_GLOBAL/bin:$PATH"

# Prefix dauerhaft in Shell-Profil eintragen
if ! grep -qs 'npm-global' "$SHELL_PROFILE" 2>/dev/null; then
  echo "export PATH=\"\$HOME/.npm-global/bin:\$PATH\"" >> "$SHELL_PROFILE"
  info "npm-global/bin zu $SHELL_PROFILE hinzugefügt."
fi

info "Installiere/aktualisiere OpenClaw..."
curl -fsSL --proto '=https' --tlsv1.2 https://openclaw.ai/install.sh | bash -s -- --no-onboard --no-prompt

if ! command -v openclaw >/dev/null 2>&1; then
  # PATH might need a refresh in this shell session
  export PATH="$HOME/.npm-global/bin:$HOME/.local/bin:$PATH"
fi

if command -v openclaw >/dev/null 2>&1; then
  ok "OpenClaw installiert ($(openclaw --version 2>/dev/null || echo 'Version unbekannt'))."
else
  fail "OpenClaw wurde installiert, ist aber nicht im PATH auffindbar. Bitte Terminal neu starten und 'openclaw --version' prüfen."
fi

# ---------------------------------------------------------------------------
# 6. Zusätzliche Build-Tools für iOS/macOS-Entwicklung
# ---------------------------------------------------------------------------

info "Installiere zusätzliche Build-Tools (git, cocoapods, watchman)..."
brew install git || true
brew install cocoapods || true
brew install watchman || true
ok "Build-Tools bereit."

# xcodebuild-Check (volles Xcode wird für echte App-Builds/Simulator gebraucht,
# CLT allein reicht nicht für iOS-Targets)
if command -v xcodebuild >/dev/null 2>&1 && xcodebuild -version >/dev/null 2>&1; then
  ok "Xcode (volle App) gefunden: $(xcodebuild -version | head -n1)"
else
  warn "Nur Command Line Tools gefunden, kein volles Xcode."
  warn "Für iOS-Simulator-Builds und App-Store-Submits lade Xcode aus dem Mac App Store:"
  warn "  https://apps.apple.com/app/xcode/id497799835"
fi

# ---------------------------------------------------------------------------
# 7. OpenClaw Onboarding automatisch starten
# ---------------------------------------------------------------------------
#
# `openclaw onboard --install-daemon` fragt interaktiv Modell-Provider/API-Key
# ab und richtet gleich den Hintergrunddienst (launchd) ein, statt nur eine
# Grundkonfiguration anzulegen. Läuft im selben Terminal weiter, der Nutzer
# beantwortet die Prompts direkt hier.

echo ""
echo "${BOLD}${GREEN}=======================================================${RESET}"
echo "${BOLD}${GREEN}  Basis-Installation abgeschlossen — jetzt Onboarding${RESET}"
echo "${BOLD}${GREEN}=======================================================${RESET}"
echo ""
echo "Installiert:"
echo "  - Xcode Command Line Tools"
echo "  - Homebrew"
echo "  - Node.js ($(node --version 2>/dev/null || echo '?'))"
echo "  - OpenClaw ($(openclaw --version 2>/dev/null || echo '?'))"
echo "  - cocoapods, watchman (für React Native / native iOS-Projekte)"
echo ""
info "Starte jetzt automatisch das vollständige OpenClaw-Onboarding (Modell-Provider, API-Key/Login, Hintergrunddienst)..."
echo ""

openclaw onboard --install-daemon || warn "Onboarding meldete einen Fehler oder wurde abgebrochen — einfach erneut ausführen mit: openclaw onboard --install-daemon"

echo ""
echo "${BOLD}${GREEN}=======================================================${RESET}"
echo "${BOLD}${GREEN}  OpenMac Installation abgeschlossen!${RESET}"
echo "${BOLD}${GREEN}=======================================================${RESET}"
echo ""
echo "${BOLD}Noch offene Schritte:${RESET}"
echo ""
echo "  1) Telegram-Bot verbinden, um deinen Agenten vom iPhone/Handy aus zu"
echo "     steuern:"
echo "       a) In Telegram mit @BotFather chatten -> https://t.me/BotFather"
echo "          -> /newbot -> Namen vergeben"
echo "       b) Den erhaltenen Bot-Token kopieren"
echo "       c) In OpenClaw eintragen:"
echo "          ${BOLD}openclaw channels add telegram${RESET}"
echo "          (fragt nach dem Bot-Token und richtet den Channel ein)"
echo ""
echo "  2) Volles Xcode aus dem Mac App Store installieren, falls noch nicht"
echo "     vorhanden (nötig für iOS-Simulator & Gerätebereitstellung):"
echo "     https://apps.apple.com/app/xcode/id497799835"
echo ""
echo "  3) iPhone per Kabel verbinden, in Xcode als Entwicklungsgerät"
echo "     freigeben (Einstellungen > Privatsphäre & Sicherheit >"
echo "     Entwicklermodus auf dem iPhone aktivieren), danach kann dein"
echo "     OpenClaw-Agent Apps bauen und direkt aufs Gerät laden."
echo ""
echo "  4) Gateway-Status jederzeit prüfen mit: ${BOLD}openclaw gateway status${RESET}"
echo "     Dashboard öffnen mit: ${BOLD}openclaw dashboard${RESET}"
echo ""
echo "Danach kannst du deinem Agenten z.B. schreiben:"
echo "  ${BOLD}\"Bau mir eine einfache iOS-App mit SwiftUI und installier sie auf meinem iPhone.\"${RESET}"
echo ""
