# shellcheck shell=dash disable=2016

___x_cmd_claw_log(){
    local ts=""
    while [ $# -gt 0 ]; do
        case "$1" in
            --help|-h)  ___x_cmd help -m claw log "$@" ; return 0 ;;
            --ts)       ts="$2" ; arg:2:shift ;;
            --get-recent-ts_)
                        ___x_cmd_claw_log___get_recent_ts_; return ;;
            *)          break ;;
        esac
    done

    local dir="$___X_CMD_CLAW_BOT_STDOUT_LOG_DIR"
    [ -d "$dir" ] || {
        claw:warn "No logs found for claw bot. Directory '$dir' does not exist."
        return 1
    }

    local CLAW_LOG_COLOR=""
    if ___x_cmd_is_stdout2tty && ___x_cmd_runmode_allow_manual; then
        CLAW_LOG_COLOR=1
    fi

    local target_ts=""
    if [ -n "$ts" ]; then
        local d best_ts=""
        for d in "$dir"/*; do
            [ -d "$d" ] || continue
            local dname="${d##*/}"
            [ "$dname" -eq "$dname" ] 2>/dev/null || continue
            [ "$dname" -le "$ts" ] 2>/dev/null || continue
            if [ -z "$best_ts" ]; then
                best_ts="$dname"
            elif [ "$dname" -gt "$best_ts" ] 2>/dev/null; then
                best_ts="$dname"
            fi
        done
        if [ -z "$best_ts" ]; then
            claw:warn "No logs found for timestamp $ts or earlier."
            return 1
        fi
        target_ts="$best_ts"
    else
        local x_=""; ___x_cmd_claw_log___get_recent_ts_ || return $?
        target_ts="$x_"
    fi

    [ -n "$target_ts" ] || return 0
    local ht; ht="$( ___x_cmd date iso "$target_ts" )"
    claw:info "Showing logs from $ht"
    ___x_cmd_claw_log___recent "$dir/$target_ts"
}

___x_cmd_claw_log___get_recent_ts_(){
    local dir="$___X_CMD_CLAW_BOT_STDOUT_LOG_DIR"
    [ -d "$dir" ] || return 1
    read -r x_ <<A
$( ___x_cmd fsiter --ls --folder "$dir" | ___x_cmd_cmds sort -r )
A
    [ -n "$x_" ]
}

___x_cmd_claw_log___recent(){
    local dir="$1"
    [ -d "$dir" ] || return 0
    ___x_cmd_claw_log___output_all "$dir"

    { ___x_cmd_is_stdout2tty && ___x_cmd_runmode_allow_manual; } || return 0

    shift $#
    local x_="" l=""
    ___x_cmd fsiter --file_ "$dir"
    while read -r l; do
        set -- "$@" "$dir/$l"
    done <<A
$x_
A
    ___x_cmd_cmds tail -F -q -n 0 "$@" | CLAW_LOG_COLOR="$CLAW_LOG_COLOR" ___x_cmd cawk -i -m date -f "$___X_CMD_ROOT_MOD/claw/lib/awk/log_output_realtime.awk"
}

___x_cmd_claw_log___output_all(){
    local dir="$1"
    [ -d "$dir" ] || return 0

    local filelist="" sep=""
    local i
    for i in "$dir"/*; do
        [ -f "$i" ] || continue
        filelist="$filelist$sep$i"
        sep="
"
    done

    [ -n "$filelist" ] || return 0

    filelist="$filelist" CLAW_LOG_COLOR="$CLAW_LOG_COLOR" ___x_cmd awk0 -m date -f "$___X_CMD_ROOT_MOD/claw/lib/awk/log_merge.awk"
}
