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

PROFILE_NAME="opencode-tinfoil"
PROFILE_SRC="profiles/${PROFILE_NAME}.jsonc"
PROFILE_DIR="${HOME}/.config/nono/profiles"
BIN_DIR="${HOME}/.local/bin"
WRAPPER_SRC="bin/opencode"

if ! command -v nono &>/dev/null; then
  echo "Error: nono is not installed. Install it first:"
  echo "  brew install nono"
  exit 1
fi

if [[ ! -f "${PROFILE_SRC}" ]]; then
  echo "Error: profile not found at ${PROFILE_SRC}"
  exit 1
fi

mkdir -p "${PROFILE_DIR}"
mkdir -p "${BIN_DIR}"

cp "${PROFILE_SRC}" "${PROFILE_DIR}/${PROFILE_NAME}.json"
chmod 644 "${PROFILE_DIR}/${PROFILE_NAME}.json"

cp "${WRAPPER_SRC}" "${BIN_DIR}/opencode"
chmod 755 "${BIN_DIR}/opencode"

nono profile validate "${PROFILE_NAME}"

echo "Installed:"
echo "  Profile: ${PROFILE_DIR}/${PROFILE_NAME}.json"
echo "  Wrapper: ${BIN_DIR}/opencode"

find_first_opencode() {
  local d c
  for d in $(printf '%s' "$PATH" | tr ':' ' '); do
    for c in "$d/opencode" "$d/opencode.exe"; do
      if [ -x "$c" ]; then
        printf '%s\n' "$c"
        return 0
      fi
    done
  done
  return 1
}

WRAPPER_OK=0
if [[ "$(find_first_opencode)" == "${BIN_DIR}/opencode" ]]; then
  WRAPPER_OK=1
fi

if [[ "${WRAPPER_OK}" -ne 1 ]]; then
  echo ""
  echo "Warning: 'opencode' on your PATH resolves to a different binary."
  echo "The sandboxed wrapper at ${BIN_DIR}/opencode will be bypassed."
  echo "Fix this with one of:"
  echo "  export PATH=\"${BIN_DIR}:\${PATH}\""
  echo "  alias opencode='${BIN_DIR}/opencode'"
fi

if [[ ":${PATH}:" != *":${BIN_DIR}:"* ]]; then
  echo ""
  echo "Warning: ${BIN_DIR} is not in your PATH."
  echo "Add this to your shell profile:"
  echo "  export PATH=\"${BIN_DIR}:\${PATH}\""
fi

echo ""
echo "Smoke test (this launches opencode inside the sandbox):"
if "${BIN_DIR}/opencode" --version; then
  echo "OK: sandboxed wrapper launches successfully."
else
  echo "Error: sandboxed wrapper failed to launch." >&2
  exit 1
fi