#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DEV_DIR="${DEV_DIR:-${ROOT_DIR}/.dev-worktree-8081}"
TARGET_REF="${1:-HEAD}"
FORCE_RECREATE="${FORCE_RECREATE:-0}"

copy_optional_path() {
  local rel_path="$1"
  local src="${ROOT_DIR}/${rel_path}"
  local dst="${DEV_DIR}/${rel_path}"
  if [[ ! -e "${src}" ]]; then
    return 0
  fi
  mkdir -p "$(dirname "${dst}")"
  cp -a "${src}" "${dst}"
}

if [[ "${DEV_DIR}" == "${ROOT_DIR}" ]]; then
  echo "DEV_DIR must not be the same as the production workspace." >&2
  exit 1
fi

if [[ -d "${DEV_DIR}/.git" && "${FORCE_RECREATE}" != "1" ]]; then
  echo "[1/6] Reusing existing dev workspace at ${DEV_DIR}"
else
  echo "[1/6] Removing previous dev workspace at ${DEV_DIR}"
  rm -rf "${DEV_DIR}"

  echo "[2/6] Cloning production workspace into isolated dev workspace"
  git clone --no-hardlinks "${ROOT_DIR}" "${DEV_DIR}" >/dev/null

  echo "[3/6] Checking out detached ref ${TARGET_REF}"
  git -C "${DEV_DIR}" checkout --detach "${TARGET_REF}" >/dev/null
fi

echo "[4/6] Copying local runtime env when available"
copy_optional_path ".env"

echo "[5/6] Copying local-only incoming design assets when available"
copy_optional_path "incoming-files/1.png"
copy_optional_path "incoming-files/260320.html"
copy_optional_path "incoming-files/sample style.css"
copy_optional_path "incoming-files/seat/center_chair_people_map(2).html"
copy_optional_path "incoming-files/reference/ledger"

echo "[6/6] Dev worktree ready"
echo "Path: ${DEV_DIR}"
echo "Use this to start 8081 from the isolated workspace:"
echo "  cd ${DEV_DIR} && docker compose -p mh-dashboard-organization-dev --env-file .env -f docker-compose.8081.yml up -d --build"
if [[ "${FORCE_RECREATE}" != "1" ]]; then
  echo "To fully rebuild the dev workspace, run:"
  echo "  FORCE_RECREATE=1 ./scripts/prepare_dev_worktree.sh"
fi
