#!/usr/bin/env bash
set -euo pipefail
# POS: communication telegram-listener — Telegram bot listener: map /command → bash, run them on chat messages
# POS_FLAGS: --enable --disable --status --sync-commands --run

CONFIG_DIR="${CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/linux_post_install}"
CONFIG_FILE="$CONFIG_DIR/telegram.env"
MAP_FILE="$CONFIG_DIR/telegram_commands.env"
API="https://api.telegram.org"
SERVICE="pos-telegram-listener.service"
USER_SYSTEMD_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"

# System prompt for the "ai " bridge: replies are posted straight into the
# chat, so ask for concise, emoji-friendly Telegram-style answers.
AI_SYSTEM="You are a friendly assistant chatting in a Telegram chat. Keep replies concise, use emojis and light formatting to make them lively, and never claim to send messages yourself."

err()  { echo "ERROR: $*" >&2; exit 1; }
log()  { echo "[+] $*"; }
warn() { echo "[!] $*" >&2; }

usage() {
    cat <<EOF
Usage: pos communication telegram listener [command]

Telegram bot listener: map /command → bash commands and run them from chat.

Commands:
  (none)       Interactive editor for the /command → bash map
  --enable     Install + start the systemd user service (autostarts on login)
  --disable    Stop + disable + remove the service
  --status     Show service state and the command map
  --sync-commands
               Push the mapped /commands to the bot's "/" menu (setMyCommands)
  --run        Run the polling loop in the foreground (used by the service)

Config:  $CONFIG_FILE  (TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID — edit with 'pos config telegram')
Map:     $MAP_FILE — '/cmd=bash command' per line (optional
         '/cmd::short description=bash command' shown in the bot menu)

Prefix a map value with '@quiet ' to run the command without replying —
for commands that already send their own notification, so you don't get it
twice (e.g. '/backup=@quiet pos system backup --send').

To reply with a command's stdout (e.g. the health dashboard), just map it
without '@quiet' and the listener forwards the output:
  '/status=pos system health'

The listener only reacts to the owner chat (TELEGRAM_CHAT_ID). Commands run
as your user, so 'sudo' inside them needs a NOPASSWD rule. The interactive
editor runs 'bash -n' to syntax-check commands before saving.

The command list is pushed to the bot's "/" menu (setMyCommands) after every
map edit, on --enable, and at daemon start; force it anytime with
--sync-commands. Telegram only accepts lowercase [a-z0-9_] names — any other
command is skipped from the menu but still resolves when typed.

Examples:
  pos communication telegram listener
  pos communication telegram listener --enable
  pos communication telegram listener --status
EOF
    exit 0
}

# ── telegram.env (same pattern as pos-communication-telegram) ────
load_config() {
    [ -f "$CONFIG_FILE" ] || return 0
    local k v
    while IFS='=' read -r k v; do
        [ -n "$k" ] || continue
        case "$k" in
            \#*) continue ;;
        esac
        v="${v%\"}"; v="${v#\"}"; v="${v%\'}"; v="${v#\'}"
        if [ -z "${!k:-}" ]; then
            export "$k"="$v"
        fi
    done < <(grep -E '^[A-Z_]+=' "$CONFIG_FILE" || true)
}

# ── command map (MAP_FILE) ──────────────────────────────────────
# Lines: /cmd=bash command, or /cmd::description=bash command. Keys keep the
# leading slash; read via awk so values may contain '='. Entries are emitted
# with a \x1f (unit separator) delimiter so bash commands may contain pipes.
# The map is re-read per message — edits apply without restarting the listener.

map_entries() {
    [ -f "$MAP_FILE" ] || return 0
    grep -E '^/[A-Za-z0-9_.-]+(::.*)?=' "$MAP_FILE" | while IFS= read -r line; do
        local left="${line%%=*}" cmd desc
        if [[ "$left" == *::* ]]; then
            cmd="${left%%::*}"
            desc="${left#*::}"
        else
            cmd="$left"
            desc=""
        fi
        printf '%s\x1f%s\x1f%s\n' "$cmd" "$desc" "${line#*=}"
    done
}

map_has() {
    [ -f "$MAP_FILE" ] || return 1
    awk -F= -v k="$1" '$1==k || index($1, k "::")==1 {found=1} END{exit !found}' "$MAP_FILE"
}

map_get() {
    [ -f "$MAP_FILE" ] || return 0
    awk -F= -v k="$1" '$1==k || index($1, k "::")==1 {sub(/^[^=]*=/,""); print}' "$MAP_FILE"
}

map_set() {
    local cmd="$1" value="$2" desc="${3:-}"
    local key="$cmd"
    mkdir -p "$CONFIG_DIR"
    touch "$MAP_FILE"
    chmod 600 "$MAP_FILE"
    local tmp
    tmp="$(mktemp)"
    [ -n "$desc" ] && key="${cmd}::${desc}"
    awk -v k="$cmd" 'index($0, k "=") != 1 && index($0, k "::") != 1 { print }' "$MAP_FILE" > "$tmp"
    printf '%s=%s\n' "$key" "$value" >> "$tmp"
    mv "$tmp" "$MAP_FILE"
    chmod 600 "$MAP_FILE"
}

map_del() {
    [ -f "$MAP_FILE" ] || return 0
    local cmd="$1" tmp
    tmp="$(mktemp)"
    awk -v k="$cmd" 'index($0, k "=") != 1 && index($0, k "::") != 1 { print }' "$MAP_FILE" > "$tmp"
    mv "$tmp" "$MAP_FILE"
    chmod 600 "$MAP_FILE"
}

MAP_CMDS=(); MAP_VALS=(); MAP_DESCS=(); MAP_N=0
load_map() {
    MAP_CMDS=(); MAP_VALS=(); MAP_DESCS=(); MAP_N=0
    [ -f "$MAP_FILE" ] || return 0
    local i=0 cmd desc value
    while IFS=$'\x1f' read -r cmd desc value; do
        [ -n "$cmd" ] || continue
        i=$((i + 1))
        MAP_CMDS[$i]="$cmd"; MAP_DESCS[$i]="$desc"; MAP_VALS[$i]="$value"
    done <<< "$(map_entries)"
    MAP_N="$i"
}

map_cmds_list() {
    load_map
    local out="" i
    for ((i=1; i<=MAP_N; i++)); do
        [ -n "$out" ] && out+=", "
        out+="${MAP_CMDS[$i]}"
    done
    printf '%s' "${out:-none}"
}

# ── Bot command menu sync (setMyCommands) ──────────────────────
# Push the mapped /commands to the bot's "/" menu so they show in the
# Telegram UI, not just resolve when typed. Runs after map edits, on
# --enable, and at daemon start; force it with --sync-commands.

description_for() {
    local value="$1" desc="${2:-}"
    if [ -n "$desc" ]; then
        printf '%s' "$desc"
        return
    fi
    value="$(strip_quiet "$value")"
    printf '%s' "${value:0:40}"
}

build_commands_json() {
    load_map
    local i name desc
    for ((i=1; i<=MAP_N; i++)); do
        name="${MAP_CMDS[$i]#/}"
        if ! [[ "$name" =~ ^[a-z][a-z0-9_]{0,31}$ ]]; then
            warn "skip '$name' from bot menu — Telegram commands are lowercase [a-z0-9_], 1-32 chars"
            continue
        fi
        desc="$(description_for "${MAP_VALS[$i]}" "${MAP_DESCS[$i]}")"
        printf '%s\t%s\n' "$name" "$desc"
    done | jq -Rr 'split("\t") | {command: .[0], description: .[1]}' | jq -sc '.'
}

sync_bot_commands() {
    load_config
    [ -n "${TELEGRAM_BOT_TOKEN:-}" ] || { warn "no bot token — run 'pos config telegram' first"; return 1; }
    command -v jq &>/dev/null || { warn "jq not found — cannot sync bot commands"; return 1; }
    local json n
    json="$(build_commands_json)"
    n="$(printf '%s' "$json" | jq 'length')"
    if curl -fsS -m 30 -X POST "${API}/bot${TELEGRAM_BOT_TOKEN}/setMyCommands" \
            --data-urlencode "commands=${json}" >/dev/null 2>&1; then
        log "bot command menu updated ($n commands)"
        return 0
    fi
    warn "setMyCommands failed"
    return 1
}

check_syntax() {
    bash -n -c "$(strip_quiet "$1")" 2>&1
}

# ── interactive editor ──────────────────────────────────────────
ui_pick() {
    load_map
    if [ "$MAP_N" -eq 0 ]; then
        warn "no commands mapped yet — add one first"
        return 1
    fi
    echo >&2
    local i
    for ((i=1; i<=MAP_N; i++)); do
        printf '  %2d) %-16s -> %s%s\n' "$i" "${MAP_CMDS[$i]}" "${MAP_VALS[$i]}" "${MAP_DESCS[$i]:+ (${MAP_DESCS[$i]})}" >&2
    done
    local idx
    read -rp "Entry number: " idx
    if ! [[ "$idx" =~ ^[0-9]+$ ]] || (( idx < 1 || idx > MAP_N )); then
        warn "invalid number '$idx'"
        return 1
    fi
    echo "$idx"
}

# Map entries may be prefixed with '@quiet ' to run the command without
# replying — for commands that deliver their own notification (e.g. backup's
# --send). The marker is stripped before running and before the editor's
# bash -n syntax check.
QUIET_PREFIX="@quiet"

strip_quiet() {
    local value="$1"
    if [ "${value#"$QUIET_PREFIX "}" != "$value" ]; then
        printf '%s' "${value#"$QUIET_PREFIX "}"
    else
        printf '%s' "$value"
    fi
}

ui_run_command() {
    local value="$1" output rc
    value="$(strip_quiet "$value")"
    echo
    echo "--- running: $value"
    if output="$(timeout 60 bash -c "$value" 2>&1)"; then
        rc=0
    else
        rc=$?
    fi
    printf '%s\n' "$output" | head -c 3800
    [ -z "$output" ] || echo
    echo "--- exit $rc"
}

ui_add() {
    local cmd value desc out
    read -rp "/command name (e.g. /status): " cmd
    [ -n "$cmd" ] || { warn "empty command name"; return; }
    case "$cmd" in
        /[A-Za-z0-9_.-]*) ;;
        *) warn "command must start with '/' and use [A-Za-z0-9_.-]: $cmd"; return ;;
    esac
    read -rp "bash command: " value
    [ -n "$value" ] || { warn "empty bash command"; return; }
    read -rp "description (optional, shown in the bot menu): " desc
    if out="$(check_syntax "$value")"; then
        map_set "$cmd" "$value" "$desc"
        sync_bot_commands || true
        log "saved $cmd -> $value"
    else
        warn "syntax error — not saved:"
        printf '%s\n' "$out" | sed 's/^/    /'
        return
    fi
    local yn
    read -rp "Test-run it now? [y/N] " yn
    case "$yn" in
        y|Y) ui_run_command "$value" ;;
    esac
}

ui_edit() {
    local idx cmd value desc out
    idx="$(ui_pick)" || return
    cmd="${MAP_CMDS[$idx]}"
    echo "Editing: $cmd -> ${MAP_VALS[$idx]}"
    read -rp "bash command: " value
    [ -n "$value" ] || { warn "empty bash command"; return; }
    read -rp "description (current: ${MAP_DESCS[$idx]:-none}): " desc
    if out="$(check_syntax "$value")"; then
        map_set "$cmd" "$value" "$desc"
        sync_bot_commands || true
        log "updated $cmd -> $value"
    else
        warn "syntax error — not saved:"
        printf '%s\n' "$out" | sed 's/^/    /'
    fi
}

ui_remove() {
    local idx cmd yn
    idx="$(ui_pick)" || return
    cmd="${MAP_CMDS[$idx]}"
    read -rp "Remove '$cmd'? [y/N] " yn
    case "$yn" in
        y|Y) map_del "$cmd"; sync_bot_commands || true; log "removed $cmd" ;;
        *) warn "canceled" ;;
    esac
}

ui_test() {
    local idx
    idx="$(ui_pick)" || return
    ui_run_command "${MAP_VALS[$idx]}"
}

ui() {
    local choice
    while true; do
        echo
        echo "Telegram listener — /command -> bash map"
        echo "-----------------------------------------"
        load_map
        if [ "$MAP_N" -eq 0 ]; then
            echo "  (no commands mapped yet)"
        else
            local i
            for ((i=1; i<=MAP_N; i++)); do
                printf '  %2d) %-16s -> %s%s\n' "$i" "${MAP_CMDS[$i]}" "${MAP_VALS[$i]}" "${MAP_DESCS[$i]:+ (${MAP_DESCS[$i]})}"
            done
        fi
        echo
        read -rp "Menu: [a]dd  [e]dit  [r]emove  [t]est  [q]uit > " choice
        case "$choice" in
            a|A|add) ui_add ;;
            e|E|edit) ui_edit ;;
            r|R|remove) ui_remove ;;
            t|T|test) ui_test ;;
            q|Q|quit|exit) echo; log "bye"; return 0 ;;
            *) warn "unknown choice '$choice'" ;;
        esac
    done
}

# ── systemd user service ────────────────────────────────────────
enable_service() {
    command -v systemctl &>/dev/null || err "systemctl not found — cannot create the listener service"
    mkdir -p "$USER_SYSTEMD_DIR"

    local runner
    if [ -x /usr/local/bin/pos-communication-telegram-listener ]; then
        runner=/usr/local/bin/pos-communication-telegram-listener
    else
        runner="$(cd "$(dirname "$0")/.." && pwd)/bin/pos-communication-telegram-listener"
        warn "using repo path $runner — re-run 'install.sh' so the service survives a deleted repo"
    fi

    cat >"$USER_SYSTEMD_DIR/$SERVICE" <<EOF
[Unit]
Description=pos Telegram listener (/command to bash)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=$runner --run
Restart=always
RestartSec=5
KillMode=control-group
TimeoutStopSec=5s
# Do NOT pin Environment=HOME here — the systemd user manager already sets the
# correct HOME for the user; pinning a stale enable-time value made the daemon
# read ~/.config/... from the wrong home (menu shows commands, daemon says unknown).

[Install]
WantedBy=default.target
EOF
    chmod 644 "$USER_SYSTEMD_DIR/$SERVICE"

    systemctl --user daemon-reload
    systemctl --user enable --now "$SERVICE"
    log "listener service enabled: $SERVICE"
    sync_bot_commands || true
    warn "commands run as $(id -un) — 'sudo' inside them needs a NOPASSWD rule"
    if command -v loginctl >/dev/null 2>&1; then
        if ! loginctl show-user "$(id -un)" 2>/dev/null | grep -q '^Linger=yes'; then
            warn "enable linger so the listener survives logout: sudo loginctl enable-linger $(id -un)"
        fi
    fi
}

disable_service() {
    if [ ! -f "$USER_SYSTEMD_DIR/$SERVICE" ]; then
        warn "no listener service installed ($SERVICE)"
        exit 0
    fi
    systemctl --user disable --now "$SERVICE" 2>/dev/null || true
    rm -f "$USER_SYSTEMD_DIR/$SERVICE"
    systemctl --user daemon-reload
    log "listener service disabled"
}

status() {
    if systemctl --user is-active --quiet "$SERVICE" 2>/dev/null; then
        echo "listener:  running"
    else
        echo "listener:  not running"
    fi
    if systemctl --user is-enabled "$SERVICE" >/dev/null 2>&1; then
        echo "autostart: enabled (starts on login)"
    else
        echo "autostart: disabled"
    fi
    echo "config:    $CONFIG_FILE"
    echo "map file:  $MAP_FILE"
    load_map
    echo "commands:  $MAP_N mapped"
    local i
    for ((i=1; i<=MAP_N; i++)); do
        printf '  %-16s -> %s%s\n' "${MAP_CMDS[$i]}" "${MAP_VALS[$i]}" "${MAP_DESCS[$i]:+ (${MAP_DESCS[$i]})}"
    done
}

# ── polling daemon ──────────────────────────────────────────────
reply() {
    local text="$1" msg_id="$2" rc="${3:-}"
    text="${text:0:3800}"
    local args=(--data-urlencode "chat_id=${TELEGRAM_CHAT_ID}" --data-urlencode "text=${text}")
    [ -n "$msg_id" ] && args+=(--data-urlencode "reply_to_message_id=${msg_id}")
    curl -fsS -m 60 -X POST "${API}/bot${TELEGRAM_BOT_TOKEN}/sendMessage" "${args[@]}" >/dev/null 2>&1 \
        || warn "reply failed (rc ${rc:-?})"
}

# Strip common markdown so AI output reads cleanly in a plain-text
# Telegram message (no parse_mode is used).
strip_markdown() {
    local t="$1"
    t="$(printf '%s' "$t" | sed -E \
        -e 's/!\[[^]]*\]\([^)]*\)//g' \
        -e 's/\[([^]]*)\]\([^)]*\)/\1/g' \
        -e 's/\*\*([^*]*)\*\*/\1/g' \
        -e 's/\*([^*]*)\*/\1/g' \
        -e 's/__([^_]*)__/\1/g' \
        -e 's/`([^`]*)`/\1/g' \
        -e 's/^[[:space:]]*#{1,6}[[:space:]]+//' \
        -e 's/^[[:space:]]*>[[:space:]]?//' \
        -e 's/^[[:space:]]*([-*+]|[0-9]+\.)[[:space:]]+/• /')"
    t="$(printf '%s' "$t" | sed -E '/^[[:space:]]*([-*_][[:space:]]*){3,}[[:space:]]*$/d')"
    printf '%s' "$t"
}

handle_message() {
    local text="$1" msg_id="$2" reply_text="${3:-}" value output rc quiet=0
    case "$text" in
        /help|/start)
            reply "Mapped commands: $(map_cmds_list)" "$msg_id"
            return ;;
    esac
    # AI bridge: non-command text starting with "ai " (case-insensitive) is
    # forwarded to Gemini; the model's answer is replied verbatim. Each chat
    # gets its own persistent memory session ("telegram-<chat_id>"); the exact
    # prompt "ai /reset" clears it. Future non-command intents (e.g. reminders)
    # slot in as more case arms here.
    if [[ "$text" != /* && "$text" =~ ^[Aa][Ii][[:space:]](.*)$ ]]; then
        local prompt="${BASH_REMATCH[1]}" answer session
        [ -n "$prompt" ] || { reply "Usage: ai <prompt> — e.g. 'ai what is Nvidia'" "$msg_id"; return; }
        session="telegram-${TELEGRAM_CHAT_ID}"
        if [[ "$prompt" =~ ^/?reset[[:space:]]*$ ]]; then
            if pos ai gemini sessions reset "$session" >/dev/null 2>&1; then
                reply "Memory cleared." "$msg_id"
            else
                reply "AI error: could not clear memory" "$msg_id"
            fi
            return
        fi
        log "ai: $prompt"
        if [ -n "$reply_text" ]; then
            prompt="[Reply context — the message you are replying to]\n${reply_text}\n\n${prompt}"
        fi
        if answer="$(timeout 120 pos ai gemini ask --session "$session" --system "$AI_SYSTEM" "$prompt" 2>&1)"; then
            reply "$(strip_markdown "$answer")" "$msg_id"
        else
            [ -n "$answer" ] || answer="timed out after 120s"
            reply "AI error: $answer" "$msg_id"
        fi
        return
    fi
    value="$(map_get "$text")"
    if [ -z "$value" ]; then
        reply "Unknown command: $text (send /help)" "$msg_id"
        return
    fi
    if [ "${value#"$QUIET_PREFIX "}" != "$value" ]; then
        quiet=1
        value="${value#"$QUIET_PREFIX "}"
    fi
    log "exec: $text"
    if output="$(timeout 60 bash -c "$value" 2>&1)"; then
        rc=0
    else
        rc=$?
    fi
    [ "$quiet" -eq 1 ] && return
    if [ -z "$output" ]; then
        output="OK"
    fi
    if [ "$rc" -ne 0 ]; then
        reply "$(printf 'exit %s\n%s' "$rc" "$output")" "$msg_id" "$rc"
    else
        reply "$output" "$msg_id"
    fi
}

run_daemon() {
    command -v jq &>/dev/null || err "jq not found (install jq — in preinstall PACKAGES)"
    load_config
    [ -n "${TELEGRAM_BOT_TOKEN:-}" ] || err "No bot token — run 'pos config telegram'"
    [ -n "${TELEGRAM_CHAT_ID:-}" ] || err "No chat id — run 'pos config telegram'"
    sync_bot_commands || true

    local offset=0
    log "listener running (owner chat ${TELEGRAM_CHAT_ID}) — Ctrl+C to stop"
    trap 'kill $(jobs -p) 2>/dev/null; exit 0' TERM INT
    while true; do
        local resp n i
        resp="$(curl -fsS -m 45 "${API}/bot${TELEGRAM_BOT_TOKEN}/getUpdates" \
            --data-urlencode "timeout=30" \
            --data-urlencode "offset=${offset}" \
            --data-urlencode 'allowed_updates=["message"]' 2>/dev/null)" || { sleep 5; continue; }
        if [ "$(printf '%s' "$resp" | jq -r '.ok // false')" != "true" ]; then
            sleep 5
            continue
        fi
        n="$(printf '%s' "$resp" | jq -r '.result | length')"
        for ((i=0; i<n; i++)); do
            local u text chat from_id msg_id reply_text
            u="$(printf '%s' "$resp" | jq -r ".result[$i].update_id")"
            text="$(printf '%s' "$resp" | jq -r ".result[$i].message.text // empty")"
            chat="$(printf '%s' "$resp" | jq -r ".result[$i].message.chat.id // empty")"
            from_id="$(printf '%s' "$resp" | jq -r ".result[$i].message.from.id // empty")"
            msg_id="$(printf '%s' "$resp" | jq -r ".result[$i].message.message_id // empty")"
            reply_text="$(printf '%s' "$resp" | jq -r ".result[$i].message.reply_to_message.text // .result[$i].message.reply_to_message.caption // empty")"
            offset=$((u + 1))
            [ -n "$text" ] || continue
            if [ -n "$chat" ] && [ "$chat" != "$TELEGRAM_CHAT_ID" ] && [ "$from_id" != "$TELEGRAM_CHAT_ID" ]; then
                continue
            fi
            handle_message "$text" "$msg_id" "$reply_text"
        done
    done
}

case "${1:-}" in
    -h|--help) usage ;;
    --enable)  enable_service ;;
    --disable) disable_service ;;
    --status)  status ;;
    --sync-commands) sync_bot_commands ;;
    --run)     run_daemon ;;
    "")        ui ;;
    *)         err "Unknown option '$1' (see --help)" ;;
esac
