#!/bin/sh
{
set -eu

NOOSFERA_OPENAI_BASE_URL="https://inference.noosfera.si/v1"
NOOSFERA_ANTHROPIC_BASE_URL="https://inference.noosfera.si"
NOOSFERA_ANTHROPIC_MODEL="noosfera/auto"
NOOSFERA_SANDBOX_DOMAIN="cloud.noosfera.si"
NOOSFERA_BLOCK_START="# >>> noosfera >>>"
NOOSFERA_BLOCK_END="# <<< noosfera <<<"

_nf_dry_run=0
_nf_no_sandbox=1
_nf_shell=""
_nf_key_env=""
_nf_key_file=""
_nf_cloud_key_env=""
_nf_key=""
_nf_cloud_key=""
_nf_trimmed=""
_nf_home=""
_nf_config_dir=""
_nf_noosfera_dir=""
_nf_env_file=""
_nf_profile=""
_nf_block_tmp=""
_nf_out_tmp=""
_nf_env_tmp=""
_nf_tty_fd_open=0
_nf_stty_saved=""
_nf_stty_target=""

_nf_restore_stty() {
  if [ -n "${_nf_stty_saved:-}" ]; then
    if [ "$_nf_stty_target" = "tty" ] && [ "$_nf_tty_fd_open" = "1" ]; then
      stty "$_nf_stty_saved" <&3 2>/dev/null || stty echo <&3 2>/dev/null || true
    elif [ "$_nf_stty_target" = "stdin" ]; then
      stty "$_nf_stty_saved" 2>/dev/null || stty echo 2>/dev/null || true
    fi
    _nf_stty_saved=""
  fi
}

_nf_cleanup() {
  _nf_restore_stty
  if [ "$_nf_tty_fd_open" = "1" ]; then
    exec 3<&- 2>/dev/null || true
    _nf_tty_fd_open=0
  fi
  if [ -n "${_nf_block_tmp:-}" ] && [ -f "$_nf_block_tmp" ]; then
    rm -f "$_nf_block_tmp"
  fi
  if [ -n "${_nf_out_tmp:-}" ] && [ -f "$_nf_out_tmp" ]; then
    rm -f "$_nf_out_tmp"
  fi
  if [ -n "${_nf_env_tmp:-}" ] && [ -f "$_nf_env_tmp" ]; then
    rm -f "$_nf_env_tmp"
  fi
}

trap '_nf_cleanup' EXIT
trap '_nf_cleanup; exit 130' INT
trap '_nf_cleanup; exit 143' TERM
trap '_nf_cleanup; exit 129' HUP

_nf_die() {
  printf 'Error: %s\n' "$1" >&2
  exit 1
}

_nf_usage() {
  cat <<'EOF'
Usage: init.sh [OPTIONS]

Configure your shell profile for Noosfera Inference and Sandboxes.

Options:
  --dry-run                Preview target profile, env file, and config without writing files
  --shell <shell>          Target shell: zsh, bash, or fish (default: auto-detect)
  --with-sandbox           Configure E2B_DOMAIN and E2B_API_KEY using NOOSFERA_CLOUD_KEY
  --no-sandbox             Skip sandbox configuration (default; kept for compatibility)
  --key-env <VAR>          Read NOOSFERA_API_KEY from environment variable VAR
  --key-file <PATH>        Read NOOSFERA_API_KEY (first line) from regular file PATH
  --cloud-key-env <VAR>    Read NOOSFERA_CLOUD_KEY from environment variable VAR
  -h, --help               Show this help message and exit

Configured environment variables (written to 0600 ~/.config/noosfera/env.{sh,fish}):
  OPENAI_BASE_URL          https://inference.noosfera.si/v1
  OPENAI_API_KEY           <your NOOSFERA_API_KEY>
  ANTHROPIC_BASE_URL       https://inference.noosfera.si
  ANTHROPIC_AUTH_TOKEN     <your NOOSFERA_API_KEY>
  ANTHROPIC_API_KEY        ""
  ANTHROPIC_MODEL          noosfera/auto
  E2B_DOMAIN               cloud.noosfera.si (only with --with-sandbox)
  E2B_API_KEY              <your NOOSFERA_CLOUD_KEY> (only with --with-sandbox)
EOF
}

_nf_parse_args() {
  while [ "$#" -gt 0 ]; do
    case "$1" in
      --dry-run)
        _nf_dry_run=1
        shift
        ;;
      --with-sandbox)
        _nf_no_sandbox=0
        shift
        ;;
      --no-sandbox)
        _nf_no_sandbox=1
        shift
        ;;
      --shell)
        [ "$#" -ge 2 ] || _nf_die "Missing value for --shell (expected zsh, bash, or fish)."
        _nf_shell="$2"
        shift 2
        ;;
      --shell=*)
        _nf_shell="${1#--shell=}"
        shift
        ;;
      --key-env)
        [ "$#" -ge 2 ] || _nf_die "Missing value for --key-env."
        _nf_key_env="$2"
        shift 2
        ;;
      --key-env=*)
        _nf_key_env="${1#--key-env=}"
        shift
        ;;
      --key-file)
        [ "$#" -ge 2 ] || _nf_die "Missing value for --key-file."
        [ -n "$2" ] || _nf_die "Missing value for --key-file."
        _nf_key_file="$2"
        shift 2
        ;;
      --key-file=*)
        _nf_key_file="${1#--key-file=}"
        [ -n "$_nf_key_file" ] || _nf_die "Missing value for --key-file."
        shift
        ;;
      --cloud-key-env)
        [ "$#" -ge 2 ] || _nf_die "Missing value for --cloud-key-env."
        _nf_cloud_key_env="$2"
        shift 2
        ;;
      --cloud-key-env=*)
        _nf_cloud_key_env="${1#--cloud-key-env=}"
        shift
        ;;
      -h|--help)
        _nf_usage
        exit 0
        ;;
      --)
        shift
        [ "$#" -eq 0 ] || _nf_die "Unexpected argument: $1 (run with --help for usage)"
        break
        ;;
      *)
        _nf_die "Unknown argument: $1 (run with --help for usage)"
        ;;
    esac
  done

  if [ -n "$_nf_key_env" ] && [ -n "$_nf_key_file" ]; then
    _nf_die "Pass either --key-env or --key-file, not both."
  fi
}

_nf_detect_shell() {
  if [ -z "$_nf_shell" ]; then
    case "${SHELL:-}" in
      */zsh|zsh) _nf_shell="zsh" ;;
      */bash|bash) _nf_shell="bash" ;;
      */fish|fish) _nf_shell="fish" ;;
      *)
        if [ -n "${ZSH_VERSION:-}" ]; then
          _nf_shell="zsh"
        elif [ -n "${FISH_VERSION:-}" ]; then
          _nf_shell="fish"
        elif [ -f "${_nf_home}/.zshrc" ]; then
          _nf_shell="zsh"
        elif [ -f "${_nf_home}/.bashrc" ]; then
          _nf_shell="bash"
        elif [ -f "${_nf_home}/.config/fish/config.fish" ]; then
          _nf_shell="fish"
        elif [ "$(uname -s 2>/dev/null || true)" = "Darwin" ]; then
          _nf_shell="zsh"
        else
          _nf_shell="bash"
        fi
        ;;
    esac
  fi

  _nf_config_dir="${_nf_home}/.config"
  _nf_noosfera_dir="${_nf_config_dir}/noosfera"

  case "$_nf_shell" in
    zsh)
      _nf_profile="${_nf_home}/.zshrc"
      _nf_env_file="${_nf_noosfera_dir}/env.sh"
      ;;
    bash)
      _nf_profile="${_nf_home}/.bashrc"
      _nf_env_file="${_nf_noosfera_dir}/env.sh"
      ;;
    fish)
      _nf_profile="${_nf_home}/.config/fish/config.fish"
      _nf_env_file="${_nf_noosfera_dir}/env.fish"
      ;;
    *) _nf_die "Unsupported shell '$_nf_shell' (expected zsh, bash, or fish)." ;;
  esac
}

_nf_is_valid_env_name() {
  (
    LC_ALL=C
    case "$1" in
      ""|[0-9]*|*[!A-Za-z0-9_]*) exit 1 ;;
      *) exit 0 ;;
    esac
  )
}

_nf_lookup_env() {
  awk 'BEGIN { printf "%s", ENVIRON[ARGV[1]]; exit 0 }' "$1"
}

_nf_invoked_as_shell() {
  case "${0##*/}" in
    sh|-sh|bash|-bash|dash|-dash|zsh|-zsh|ash|-ash|ksh|-ksh|mksh|-mksh)
      return 0
      ;;
    *)
      return 1
      ;;
  esac
}

_nf_read_line_stdin() {
  _nf_key=""
  if IFS= read -r _nf_key; then
    return 0
  fi
  [ -n "${_nf_key:-}" ]
}

_nf_read_line_fd3() {
  _nf_key=""
  if IFS= read -r _nf_key <&3; then
    return 0
  fi
  [ -n "${_nf_key:-}" ]
}

_nf_trim_value() {
  _nf_trimmed=$(printf '%s' "$1" | tr -d '\r')
  while :; do
    case "$_nf_trimmed" in
      " "*|"	"*) _nf_trimmed=${_nf_trimmed#?} ;;
      *) break ;;
    esac
  done
  while :; do
    case "$_nf_trimmed" in
      *" "|*"	") _nf_trimmed=${_nf_trimmed%?} ;;
      *) break ;;
    esac
  done
}

_nf_validate_secret() {
  _nf_label="$1"
  _nf_trim_value "$2"
  _nf_req_prefix="$3"
  [ -n "$_nf_trimmed" ] || _nf_die "$_nf_label is required and cannot be empty."
  case "$_nf_trimmed" in
    -*) _nf_die "$_nf_label must not start with '-'." ;;
  esac
  if [ -n "$_nf_req_prefix" ]; then
    case "$_nf_trimmed" in
      "${_nf_req_prefix}"*) ;;
      *) _nf_die "$_nf_label must start with '${_nf_req_prefix}'." ;;
    esac
  fi
  [ "${#_nf_trimmed}" -ge 6 ] || _nf_die "$_nf_label must be at least 6 characters."
  if ! (
    LC_ALL=C
    case "$_nf_trimmed" in
      *[!A-Za-z0-9_.:/+@~=-]*) exit 1 ;;
      *) exit 0 ;;
    esac
  ); then
    _nf_die "$_nf_label contains unsupported characters or whitespace."
  fi
}

_nf_validate_key() {
  _nf_validate_secret "NOOSFERA_API_KEY" "$_nf_key" "nsk_"
  _nf_key="$_nf_trimmed"
}

_nf_read_key_file() {
  _nf_kf="$1"
  [ -L "$_nf_kf" ] && _nf_die "Key file must not be a symlink: $_nf_kf"
  [ -e "$_nf_kf" ] || _nf_die "Key file does not exist: $_nf_kf"
  [ -f "$_nf_kf" ] || _nf_die "Key file must be a regular file: $_nf_kf"
  [ -r "$_nf_kf" ] || _nf_die "Key file is not readable: $_nf_kf"
  _nf_key=""
  if ! IFS= read -r _nf_key < "$_nf_kf"; then
    [ -n "${_nf_key:-}" ] || _nf_die "NOOSFERA_API_KEY in key file is empty."
  fi
  _nf_validate_key
}

_nf_resolve_key() {
  if [ -n "$_nf_key_file" ]; then
    _nf_read_key_file "$_nf_key_file"
    return 0
  fi

  if [ -n "$_nf_key_env" ]; then
    _nf_is_valid_env_name "$_nf_key_env" || _nf_die "Invalid environment variable name for --key-env."
    _nf_key=$(_nf_lookup_env "$_nf_key_env")
    _nf_trim_value "$_nf_key"
    [ -n "$_nf_trimmed" ] || _nf_die "Environment variable $_nf_key_env is empty or unset."
    _nf_key="$_nf_trimmed"
    _nf_validate_key
    return 0
  fi

  if [ -n "${NOOSFERA_API_KEY:-}" ]; then
    _nf_key="$NOOSFERA_API_KEY"
    _nf_validate_key
    return 0
  fi

  if [ "$_nf_dry_run" = "1" ]; then
    if [ ! -t 0 ] && ! _nf_invoked_as_shell; then
      _nf_read_line_stdin || true
      if [ -n "${_nf_key:-}" ]; then
        _nf_validate_key
      fi
    fi
    return 0
  fi

  if [ -t 0 ]; then
    _nf_stty_target="stdin"
    _nf_stty_saved=$(stty -g 2>/dev/null || true)
    stty -echo 2>/dev/null || true
    printf '%s' "Enter NOOSFERA_API_KEY (nsk_..., input hidden): " >&2
    _nf_read_line_stdin || true
    _nf_restore_stty
    stty echo 2>/dev/null || true
    printf '\n' >&2
    _nf_validate_key
    return 0
  fi

  if _nf_invoked_as_shell; then
    if exec 3</dev/tty 2>/dev/null; then
      _nf_tty_fd_open=1
      if [ -t 3 ]; then
        _nf_stty_target="tty"
        _nf_stty_saved=$(stty -g <&3 2>/dev/null || true)
        stty -echo <&3 2>/dev/null || true
      fi
      printf '%s' "Enter NOOSFERA_API_KEY (nsk_..., input hidden): " >/dev/tty 2>/dev/null || \
        printf '%s' "Enter NOOSFERA_API_KEY (nsk_..., input hidden): " >&2
      _nf_read_line_fd3 || true
      _nf_restore_stty
      [ -t 3 ] && stty echo <&3 2>/dev/null || true
      printf '\n' >/dev/tty 2>/dev/null || printf '\n' >&2
      exec 3<&- 2>/dev/null || true
      _nf_tty_fd_open=0
      _nf_validate_key
      return 0
    fi
    _nf_die "NOOSFERA_API_KEY is required (set NOOSFERA_API_KEY, pass --key-env, or pass --key-file when running non-interactively)."
  fi

  _nf_read_line_stdin || true
  _nf_validate_key
}

_nf_resolve_cloud_key() {
  if [ "$_nf_no_sandbox" = "1" ]; then
    _nf_cloud_key=""
    return 0
  fi

  if [ -n "$_nf_cloud_key_env" ]; then
    _nf_is_valid_env_name "$_nf_cloud_key_env" || _nf_die "Invalid environment variable name for --cloud-key-env."
    _nf_cloud_key=$(_nf_lookup_env "$_nf_cloud_key_env")
    _nf_trim_value "$_nf_cloud_key"
    [ -n "$_nf_trimmed" ] || _nf_die "Environment variable $_nf_cloud_key_env is empty or unset."
    _nf_validate_secret "NOOSFERA_CLOUD_KEY" "$_nf_trimmed" ""
    _nf_cloud_key="$_nf_trimmed"
    return 0
  fi

  if [ -n "${NOOSFERA_CLOUD_KEY:-}" ]; then
    _nf_validate_secret "NOOSFERA_CLOUD_KEY" "$NOOSFERA_CLOUD_KEY" ""
    _nf_cloud_key="$_nf_trimmed"
    return 0
  fi

  if [ "$_nf_dry_run" = "1" ]; then
    _nf_cloud_key=""
    return 0
  fi

  _nf_die "NOOSFERA_CLOUD_KEY is required with --with-sandbox (sandboxes use a separate key from NOOSFERA_API_KEY). Set NOOSFERA_CLOUD_KEY or omit --with-sandbox."
}

_nf_emit_var() {
  if [ "$_nf_shell" = "fish" ]; then
    printf "set -gx -- %s '%s'\n" "$1" "$2"
  else
    printf "export %s='%s'\n" "$1" "$2"
  fi
}

_nf_render_env_file() {
  _nf_api_val="$1"
  _nf_sandbox_val="${2:-}"
  _nf_emit_var OPENAI_BASE_URL "$NOOSFERA_OPENAI_BASE_URL"
  _nf_emit_var OPENAI_API_KEY "$_nf_api_val"
  _nf_emit_var ANTHROPIC_BASE_URL "$NOOSFERA_ANTHROPIC_BASE_URL"
  _nf_emit_var ANTHROPIC_AUTH_TOKEN "$_nf_api_val"
  _nf_emit_var ANTHROPIC_API_KEY ""
  _nf_emit_var ANTHROPIC_MODEL "$NOOSFERA_ANTHROPIC_MODEL"
  if [ "$_nf_no_sandbox" = "0" ]; then
    _nf_emit_var E2B_DOMAIN "$NOOSFERA_SANDBOX_DOMAIN"
    _nf_emit_var E2B_API_KEY "$_nf_sandbox_val"
  fi
}

_nf_render_profile_block() {
  printf '%s\n' "$NOOSFERA_BLOCK_START"
  if [ "$_nf_shell" = "fish" ]; then
    printf '%s\n' 'test -f "$HOME/.config/noosfera/env.fish"; and source "$HOME/.config/noosfera/env.fish"'
  else
    printf '%s\n' '[ -f "$HOME/.config/noosfera/env.sh" ] && . "$HOME/.config/noosfera/env.sh"'
  fi
  printf '%s\n' "$NOOSFERA_BLOCK_END"
}

_nf_check_no_symlink() {
  [ -L "$1" ] && _nf_die "Refusing symlink path: $1"
  return 0
}

_nf_ensure_dir() {
  _nf_dir="$1"
  _nf_check_no_symlink "$_nf_dir"
  if [ -e "$_nf_dir" ]; then
    [ -d "$_nf_dir" ] || _nf_die "Expected directory at $_nf_dir"
  else
    mkdir -p "$_nf_dir"
  fi
}

_nf_write_profile() {
  _nf_old_umask=$(umask)
  umask 077

  _nf_profile_dir="${_nf_profile%/*}"
  [ -n "$_nf_profile_dir" ] || _nf_profile_dir="/"

  _nf_ensure_dir "$_nf_config_dir"
  _nf_ensure_dir "$_nf_noosfera_dir"
  chmod 0700 "$_nf_noosfera_dir"

  _nf_check_no_symlink "$_nf_env_file"
  if [ -e "$_nf_env_file" ] && [ ! -f "$_nf_env_file" ]; then
    _nf_die "Expected regular file at $_nf_env_file"
  fi

  if [ "$_nf_shell" = "fish" ]; then
    _nf_ensure_dir "${_nf_config_dir}/fish"
  elif [ ! -d "$_nf_profile_dir" ]; then
    mkdir -p "$_nf_profile_dir"
  fi

  _nf_check_no_symlink "$_nf_profile"
  if [ -e "$_nf_profile" ] && [ ! -f "$_nf_profile" ]; then
    _nf_die "Expected regular file at $_nf_profile"
  fi

  _nf_env_tmp=$(mktemp "${_nf_noosfera_dir}/.env.XXXXXX")
  _nf_render_env_file "$_nf_key" "$_nf_cloud_key" > "$_nf_env_tmp"
  chmod 0600 "$_nf_env_tmp"
  mv "$_nf_env_tmp" "$_nf_env_file"
  _nf_env_tmp=""

  if [ "$_nf_profile_dir" = "/" ]; then
    _nf_tmp_prefix="/"
  else
    _nf_tmp_prefix="${_nf_profile_dir}/"
  fi

  _nf_block_tmp=$(mktemp "${_nf_tmp_prefix}.noosfera-block.XXXXXX")
  _nf_out_tmp=$(mktemp "${_nf_tmp_prefix}.noosfera-profile.XXXXXX")
  _nf_render_profile_block > "$_nf_block_tmp"

  if [ -f "$_nf_profile" ]; then
    _nf_src="$_nf_profile"
  else
    _nf_src="/dev/null"
  fi

  awk -v start_mark="$NOOSFERA_BLOCK_START" -v end_mark="$NOOSFERA_BLOCK_END" '
    NR == FNR {
      block = (NR == 1 ? $0 : block "\n" $0)
      next
    }
    $0 == start_mark {
      if (!replaced) {
        print block
        replaced = 1
      }
      skip = 1
      last_blank = 0
      next
    }
    $0 == end_mark {
      if (skip) {
        skip = 0
        next
      }
    }
    !skip {
      print
      last_blank = ($0 == "")
      saw_line = 1
    }
    END {
      if (!replaced) {
        if (saw_line && !last_blank) print ""
        print block
      }
    }
  ' "$_nf_block_tmp" "$_nf_src" > "$_nf_out_tmp"

  chmod 0600 "$_nf_out_tmp"
  mv "$_nf_out_tmp" "$_nf_profile"
  _nf_out_tmp=""
  rm -f "$_nf_block_tmp"
  _nf_block_tmp=""
  umask "$_nf_old_umask"
}

_nf_print_next_steps() {
  _nf_sandbox_status="disabled"
  if [ "$_nf_no_sandbox" = "0" ]; then
    _nf_sandbox_status="enabled"
  fi

  if [ "$_nf_dry_run" = "1" ]; then
    printf 'Dry run: no files were written.\n'
    printf 'Target profile: %s (shell: %s, sandbox: %s)\n' "$_nf_profile" "$_nf_shell" "$_nf_sandbox_status"
    printf 'Target env file: %s (mode 0600)\n\n' "$_nf_env_file"
    printf '# Profile block (%s):\n' "$_nf_profile"
    _nf_render_profile_block
    printf '\n# Secret env file (%s):\n' "$_nf_env_file"
    _nf_render_env_file "<NOOSFERA_API_KEY>" "<NOOSFERA_CLOUD_KEY>"
    printf '\nRun without --dry-run to write these files, then reload your shell and run claude or codex.\n'
    return 0
  fi

  printf 'Configured Noosfera environment in %s (secrets in %s, shell: %s, sandbox: %s)\n\n' \
    "$_nf_profile" "$_nf_env_file" "$_nf_shell" "$_nf_sandbox_status"
  printf 'Next steps:\n'
  if [ "$_nf_shell" = "fish" ]; then
    printf '  1. Reload your shell:\n       source "%s"\n' "$_nf_profile"
  else
    printf '  1. Reload your shell:\n       . "%s"\n' "$_nf_profile"
  fi
  printf '  2. Start coding with:\n'
  printf '       claude\n'
  printf '       codex\n'
  printf '     Or use any OpenAI / Anthropic Python or Node SDK.\n'
}

main() {
  _nf_parse_args "$@"
  [ -n "${HOME:-}" ] || _nf_die "HOME is not set."
  while :; do
    case "$HOME" in
      /) break ;;
      */) HOME="${HOME%/}" ;;
      *) break ;;
    esac
  done
  case "$HOME" in
    /) _nf_home="" ;;
    *) _nf_home="$HOME" ;;
  esac
  _nf_detect_shell
  _nf_resolve_key
  _nf_resolve_cloud_key
  if [ "$_nf_dry_run" = "0" ]; then
    _nf_write_profile
  fi
  _nf_print_next_steps
}

main "$@"
}
