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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=common.sh
source "${SCRIPT_DIR}/common.sh"

HOST_OS="$(detect_os)"
HOST_ARCH="$(detect_arch)"
LIMA_VM_NAME="${EUV_LIMA_VM_NAME:-euv-linux}"
LIMA_TEMPLATE="${EUV_LIMA_TEMPLATE:-template:ubuntu-lts}"
LIMA_CPUS="${EUV_LIMA_CPUS:-4}"
LIMA_MEMORY="${EUV_LIMA_MEMORY:-4}"
LIMA_DISK="${EUV_LIMA_DISK:-20}"

RUN_ALL_MOBILE=0
for arg in "$@"; do
  if [ "${arg}" = "--all" ]; then
    RUN_ALL_MOBILE=1
  fi
done

log_info "Provisioning Linux VM (QEMU + Lima) & emulator infrastructure (${HOST_OS}/${HOST_ARCH})..."

if [ "${HOST_OS}" = "macos" ]; then
  if ! command -v brew >/dev/null 2>&1; then
    log_error "Homebrew is required to install qemu and lima on macOS."
    exit 1
  fi
  if ! command -v qemu-system-aarch64 >/dev/null 2>&1; then
    log_info "Installing QEMU via Homebrew..."
    brew_install_formula qemu
  fi
  if ! command -v limactl >/dev/null 2>&1; then
    log_info "Installing Lima via Homebrew..."
    brew_install_formula lima
  fi

  VM_STATUS="$(limactl list --format '{{.Name}} {{.Status}}' 2>/dev/null | awk -v name="${LIMA_VM_NAME}" '$1 == name { print $2 }' || true)"
  if [ -z "${VM_STATUS}" ]; then
    log_info "Creating and starting lightweight ARM64 Linux VM '${LIMA_VM_NAME}' (${LIMA_TEMPLATE}, cpus=${LIMA_CPUS}, mem=${LIMA_MEMORY}GiB, disk=${LIMA_DISK}GiB)..."
    limactl start \
      --name="${LIMA_VM_NAME}" \
      --tty=false \
      --cpus="${LIMA_CPUS}" \
      --memory="${LIMA_MEMORY}" \
      --disk="${LIMA_DISK}" \
      "${LIMA_TEMPLATE}"
  elif [ "${VM_STATUS}" != "Running" ]; then
    log_info "Starting existing Lima Linux VM '${LIMA_VM_NAME}' (current status=${VM_STATUS})..."
    limactl start --tty=false "${LIMA_VM_NAME}"
  else
    log_info "Lima Linux VM '${LIMA_VM_NAME}' is already running."
  fi

  log_info "Lima VM kernel: $(limactl shell "${LIMA_VM_NAME}" uname -a)"
else
  log_info "Running on Linux host directly; Lima VM bootstrap skipped."
fi

if command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then
  log_info "Docker Linux engine ready: $(docker info --format '{{.OperatingSystem}} / {{.Architecture}} ({{.KernelVersion}})' 2>/dev/null || echo available)"
else
  log_warn "Docker daemon is not running; Lima Linux VM remains available for Linux native/TUI/CLI verification."
fi

if [ "${RUN_ALL_MOBILE}" = "1" ]; then
  "${SCRIPT_DIR}/setup-apple.sh"
  "${SCRIPT_DIR}/setup-android.sh"
  "${SCRIPT_DIR}/setup-harmony.sh"
fi

write_local_env
log_info "VM & emulator environment setup complete."
