#!/bin/mksh
# Interactive mksh configuration
# Source login profile if not already loaded
[ -z "$EDITOR" ] && . "$HOME/.profile"

# Vi mode
set -o vi

# Prompt: user@host:dir >
PS1='$(print -n "\033[34m")${USER}$(print -n "\033[0m")@$(print -n "\033[35m")$(hostname -s)$(print -n "\033[0m"):$(print -n "\033[36m")${PWD/#$HOME/\~}$(print -n "\033[0m") > '

# History
HISTFILE="$HOME/.mksh_history"
HISTSIZE=10000

# Source config modules
. "$HOME/.config/.mksh/load.sh"

# Zoxide (smarter cd)
command -v zoxide >/dev/null 2>&1 && eval "$(zoxide init posix --hook prompt)"

# Direnv (bash hook works under mksh; there is no dedicated ksh hook)
command -v direnv >/dev/null 2>&1 && eval "$(direnv hook bash)"

# History logging (encrypted with SQLCipher)
_kh_db="$HOME/.local/share/history/history.db"
_kh_key_file="$HOME/.local/share/history/.key"

_kh_log() {
	typeset cmd="$1" exit_code="$2" pwd_path="$PWD"
	[ -z "$cmd" ] && return
	case "$cmd" in history*) return ;; esac
	[ -f "$_kh_key_file" ] || return
	[ -f "$_kh_db" ] || return
	typeset escaped_cmd=$(print -r -- "$cmd" | sed "s/'/''/g")
	typeset escaped_pwd=$(print -r -- "$pwd_path" | sed "s/'/''/g")
	typeset key=$(cat "$_kh_key_file")
	(sqlcipher "$_kh_db" "PRAGMA key = '$key'; INSERT INTO terminal_history (command, exit_code, pwd, shell) VALUES ('$escaped_cmd', $exit_code, '$escaped_pwd', 'mksh');" &) >/dev/null 2>&1
}

# Command history logging hook.
if [ -n "$BASH_VERSION" ]; then
	# bash: DEBUG trap captures the command, PROMPT_COMMAND logs it
	_kh_last_cmd=""
	trap '_kh_last_cmd=$(fc -ln -1 2>/dev/null | sed "s/^[[:space:]]*//")' DEBUG
	PROMPT_COMMAND='_kh_log "$_kh_last_cmd" "$?"'
else
	# mksh: no DEBUG trap / PROMPT_COMMAND. Log from PS1 each prompt.
	# The leading $(...) captures $? first, so the exit code is accurate,
	# and _kh_prompt emits nothing so the visible prompt is unchanged.
	_kh_prompt() {
		_kh_log "$(fc -ln -1 2>/dev/null | sed 's/^[[:space:]]*//')" "$1"
	}
	PS1='$(_kh_prompt "$?")'"$PS1"
fi
