#!/usr/bin/env bash
set -euo pipefail

VERSION="1.2.6"
BASE_URL="${BASE_URL:-https://www.flushnet.net/api/downloads/ubuntu/1.2.6/payload}"
SCRIPT_DIR="$(cd "$(dirname "$0")" 2>/dev/null && pwd || true)"
LOCAL_PAYLOAD="${LOCAL_PAYLOAD:-${SCRIPT_DIR:+$SCRIPT_DIR/payload}}"
INSTALL_DIR="${INSTALL_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/flushnet-runtime}"
SYSTEMD_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
BIN_DIR="${HOME}/.local/bin"
ACCESS_CODE="${ACCESS_CODE:-}"
START_NOW=0
ENABLE_SERVICE=1
INSTALL_BROWSER=0

usage() {
  cat <<EOF
Flushnet AI Runner Ubuntu CLI ${VERSION}

Usage: $(basename "$0") [options]
  --install-dir PATH       Install location (default: $INSTALL_DIR)
  --access-code CODE       Link this Ubuntu machine during install
  --start-now              Start the runtime after configuration
  --no-systemd             Do not install the systemd user service
  --with-browser           Install Playwright Chromium for browser profiles
  -h, --help               Show this help

After install:
  flushnet-ai-runner configure
  flushnet-ai-runner start
  flushnet-ai-runner status
  flushnet-ai-runner ui
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --install-dir) INSTALL_DIR="$2"; shift 2 ;;
    --access-code) ACCESS_CODE="$2"; shift 2 ;;
    --start-now) START_NOW=1; shift ;;
    --no-systemd) ENABLE_SERVICE=0; shift ;;
    --with-browser) INSTALL_BROWSER=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) echo "Unknown option: $1" >&2; usage >&2; exit 2 ;;
  esac
done

[[ "$(uname -s)" == "Linux" ]] || { echo "This installer is for Linux/Ubuntu." >&2; exit 1; }

ensure_bootstrap_tools() {
  local missing=()
  command -v curl >/dev/null 2>&1 || missing+=(curl)
  command -v python3 >/dev/null 2>&1 || missing+=(python3)
  command -v tar >/dev/null 2>&1 || missing+=(tar)
  command -v xz >/dev/null 2>&1 || missing+=(xz-utils)
  command -v sha256sum >/dev/null 2>&1 || missing+=(coreutils)
  if ((${#missing[@]})); then
    echo "Missing prerequisites: ${missing[*]}" >&2
    echo "Install them with your Ubuntu package manager, then rerun this installer." >&2
    exit 1
  fi
}

install_node_runtime() {
  if [[ -x "$INSTALL_DIR/node/bin/node" ]]; then
    local major
    major="$("$INSTALL_DIR/node/bin/node" -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)"
    [[ "$major" =~ ^[0-9]+$ && "$major" -ge 18 ]] && return 0
  fi
  local arch node_arch idx version tarball tmp expected actual
  arch="$(uname -m)"
  case "$arch" in
    x86_64|amd64) node_arch=x64 ;;
    aarch64|arm64) node_arch=arm64 ;;
    *) echo "Unsupported Ubuntu CPU architecture: $arch" >&2; exit 1 ;;
  esac
  tmp="$(mktemp -d)"
  idx="$tmp/index.json"
  curl -fsSL https://nodejs.org/dist/index.json -o "$idx"
  version="$(python3 - "$idx" <<'PY'
import json,sys
rows=json.load(open(sys.argv[1],encoding='utf-8'))
for row in rows:
    v=str(row.get('version',''))
    try: major=int(v.lstrip('v').split('.')[0])
    except Exception: continue
    if row.get('lts') and major >= 20:
        print(v); break
PY
)"
  [[ -n "$version" ]] || { echo "Could not resolve a supported Node.js LTS release." >&2; exit 1; }
  tarball="node-${version}-linux-${node_arch}.tar.xz"
  echo "Installing bundled Node.js ${version} (${node_arch})..."
  curl -fsSL "https://nodejs.org/dist/${version}/${tarball}" -o "$tmp/$tarball"
  curl -fsSL "https://nodejs.org/dist/${version}/SHASUMS256.txt" -o "$tmp/SHASUMS256.txt"
  expected="$(awk -v f="$tarball" '$2==f {print $1}' "$tmp/SHASUMS256.txt")"
  actual="$(sha256sum "$tmp/$tarball" | awk '{print $1}')"
  [[ -n "$expected" && "$actual" == "$expected" ]] || { echo "Node.js SHA-256 verification failed." >&2; exit 1; }
  rm -rf "$INSTALL_DIR/node"
  mkdir -p "$INSTALL_DIR/node"
  tar -xJf "$tmp/$tarball" -C "$INSTALL_DIR/node" --strip-components=1
  rm -rf "$tmp"
}

runtime_files=(
  flushnet-runtime-bundle.js flushnet-local-bridge.js flushnet-local-bridge.cjs
  connect-v2.mjs mcp-oauth.mjs configure.sh headless-v86-sandbox-launcher.js
  package.json version.json config_template.json start.sh stop.sh status.sh
  open_desktop_ui.sh update.sh uninstall.sh
)

download_runtime() {
  mkdir -p "$INSTALL_DIR"
  for f in "${runtime_files[@]}"; do
    if [[ -n "${LOCAL_PAYLOAD:-}" && -f "$LOCAL_PAYLOAD/$f" ]]; then
      echo "Installing $f"
      cp "$LOCAL_PAYLOAD/$f" "$INSTALL_DIR/$f"
    else
      echo "Downloading $f"
      curl -fsSL "$BASE_URL/$f" -o "$INSTALL_DIR/$f"
    fi
  done
  chmod 0755 "$INSTALL_DIR"/*.sh
  [[ -f "$INSTALL_DIR/config.json" ]] || cp "$INSTALL_DIR/config_template.json" "$INSTALL_DIR/config.json"
}

install_dependencies() {
  export PATH="$INSTALL_DIR/node/bin:$PATH"
  export PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
  export PUPPETEER_SKIP_DOWNLOAD=1
  export PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=1
  (cd "$INSTALL_DIR" && npm install --omit=dev --no-audit --no-fund)
  if [[ "$INSTALL_BROWSER" == "1" && -x "$INSTALL_DIR/node_modules/.bin/playwright" ]]; then
    echo "Installing Chromium for Linux browser profiles..."
    (cd "$INSTALL_DIR" && PLAYWRIGHT_BROWSERS_PATH="$INSTALL_DIR/ms-playwright" "$INSTALL_DIR/node_modules/.bin/playwright" install chromium)
  fi
}

install_cli_wrapper() {
  mkdir -p "$BIN_DIR"
  cat > "$BIN_DIR/flushnet-ai-runner" <<EOF
#!/usr/bin/env bash
set -euo pipefail
RUNTIME_DIR=$(printf '%q' "$INSTALL_DIR")
cmd="\${1:-status}"; shift || true
case "\$cmd" in
  start) exec "\$RUNTIME_DIR/start.sh" "\$@" ;;
  stop) exec "\$RUNTIME_DIR/stop.sh" "\$@" ;;
  status) exec "\$RUNTIME_DIR/status.sh" "\$@" ;;
  configure) exec "\$RUNTIME_DIR/configure.sh" "\$@" ;;
  ui|desktop) exec "\$RUNTIME_DIR/open_desktop_ui.sh" "\$@" ;;
  logs) exec tail -n 200 -f "\$RUNTIME_DIR"/logs/*.log ;;
  restart) "\$RUNTIME_DIR/stop.sh" || true; exec "\$RUNTIME_DIR/start.sh" ;;
  *) echo "Usage: flushnet-ai-runner {start|stop|restart|status|configure|ui|logs}" >&2; exit 2 ;;
esac
EOF
  chmod 0755 "$BIN_DIR/flushnet-ai-runner"
}

install_systemd_user_service() {
  [[ "$ENABLE_SERVICE" == "1" ]] || return 0
  command -v systemctl >/dev/null 2>&1 || { echo "systemctl not found; skipping user service."; return 0; }
  mkdir -p "$SYSTEMD_DIR"
  cat > "$SYSTEMD_DIR/flushnet-ai-runner.service" <<EOF
[Unit]
Description=Flushnet AI Runner Runtime
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
RemainAfterExit=yes
Environment="FLUSHNET_RUNTIME_HOME=$INSTALL_DIR"
Environment="PATH=$INSTALL_DIR/node/bin:/usr/local/bin:/usr/bin:/bin"
ExecStart=/bin/bash "$INSTALL_DIR/start.sh"
ExecStop=/bin/bash "$INSTALL_DIR/stop.sh"
TimeoutStartSec=60
TimeoutStopSec=30

[Install]
WantedBy=default.target
EOF
  systemctl --user daemon-reload >/dev/null 2>&1 || true
}

config_is_linked() {
  python3 - "$INSTALL_DIR/config.json" <<'PY'
import json,sys
try: d=json.load(open(sys.argv[1],encoding='utf-8'))
except Exception: d={}
print('yes' if d.get('node_id') and d.get('owner_id') and d.get('token') else 'no')
PY
}

ensure_bootstrap_tools
mkdir -p "$INSTALL_DIR"
install_node_runtime
download_runtime
install_dependencies
install_cli_wrapper
install_systemd_user_service

if [[ -n "$ACCESS_CODE" ]]; then
  ACCESS_CODE="$ACCESS_CODE" "$INSTALL_DIR/configure.sh" "$ACCESS_CODE"
fi

if [[ "$START_NOW" == "1" ]]; then
  if [[ "$(config_is_linked)" != "yes" ]]; then
    echo "Runtime is installed but not linked. Run: flushnet-ai-runner configure" >&2
    exit 3
  fi
  if [[ "$ENABLE_SERVICE" == "1" ]] && command -v systemctl >/dev/null 2>&1; then
    systemctl --user enable --now flushnet-ai-runner.service
  else
    "$INSTALL_DIR/start.sh"
  fi
fi

cat <<EOF

Flushnet AI Runner Ubuntu CLI ${VERSION} installed.
Runtime: $INSTALL_DIR
Command: $BIN_DIR/flushnet-ai-runner

Next steps:
  1. Link the machine:  flushnet-ai-runner configure
  2. Start runtime:      flushnet-ai-runner start
  3. Check status:       flushnet-ai-runner status
  4. Open Desktop UI:    flushnet-ai-runner ui
EOF
if [[ "$ENABLE_SERVICE" == "1" ]]; then
  echo "Optional autostart after linking: systemctl --user enable --now flushnet-ai-runner.service"
fi
