# shellcheck shell=dash disable=2016

___x_cmd_claw_log(){
    local since="" last="" all="" CLAW_LOG_DEBUG=""
    while [ $# -gt 0 ]; do
        case "$1" in
            --help|-h)      ___x_cmd help -m claw log "$@" ; return 0 ;;
            --since)        since="$2" ; arg:2:shift ;;
            --last)         last="$2" ; arg:2:shift ;;
            --all)          all=1 ; shift ;;
            --debug)        CLAW_LOG_DEBUG=1 ; 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 CLAW_LOG_SINCE_TS="" CLAW_LOG_LIMIT=""

    if [ -n "$all" ]; then
        :
    elif [ -n "$since" ]; then
        local x_=""
        ___x_cmd_claw_log___since_ts_ "$since" || {
            claw:warn "Invalid --since value: $since (expected duration like 1h/30m/2d, or a timestamp)"
            return 1
        }
        CLAW_LOG_SINCE_TS="$x_"
    elif [ -n "$last" ]; then
        :   # --last without --since means last N entries across all history
    else
        # default: last 50 entries
        CLAW_LOG_LIMIT=50
    fi

    if [ -n "$last" ]; then
        case "$last" in
            *[!0-9]*)
                claw:warn "Invalid --last value: $last (must be a positive integer)"
                return 1
                ;;
        esac
        [ "$last" -gt 0 ] 2>/dev/null || {
            claw:warn "Invalid --last value: $last (must be a positive integer)"
            return 1
        }
        CLAW_LOG_LIMIT="$last"
    fi

    local target_ts=""
    local x_=""; ___x_cmd_claw_log___get_recent_ts_ || return $?
    target_ts="$x_"

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

    if [ -n "$all" ]; then
        claw:info "Showing all logs"
    elif [ -n "$CLAW_LOG_SINCE_TS" ]; then
        local ht; ht="$( ___x_cmd date iso "$CLAW_LOG_SINCE_TS" )"
        claw:info "Showing logs since $ht"
    elif [ -n "$CLAW_LOG_LIMIT" ]; then
        claw:info "Showing last $CLAW_LOG_LIMIT log entries"
    else
        claw:info "Showing recent logs"
    fi

    CLAW_LOG_SINCE_TS="$CLAW_LOG_SINCE_TS" \
    CLAW_LOG_LIMIT="$CLAW_LOG_LIMIT" \
    CLAW_LOG_COLOR="$CLAW_LOG_COLOR" \
    CLAW_LOG_DEBUG="$CLAW_LOG_DEBUG" \
        ___x_cmd_claw_log___recent "$dir/$target_ts" "$dir"
}

___x_cmd_claw_log___since_ts_(){
    local since="$1"
    local now=""
    ___x_cmd date timestamp_ || return 1
    now="$x_"
    local total=0 n=0 n_raw="" unit="" rest="$since"

    # pure unix timestamp
    case "$since" in
        ''|*[!0-9]*) ;;
        *)  x_="$since"
            return 0
            ;;
    esac

    # duration: e.g. 1h, 30m, 2d, 1w, 1h30m
    case "$since" in
        *[!0-9smhdw]*) ;;
        *)  while [ -n "$rest" ]; do
                n_raw="${rest%%[!0-9]*}"
                [ -n "$n_raw" ] || return 1

                # strip leading zeros to avoid dash octal interpretation
                n="$n_raw"
                while [ "${n#0}" != "$n" ]; do n="${n#0}"; done
                [ -n "$n" ] || n=0

                unit="${rest#$n_raw}"
                unit="${unit%"${unit#?}"}"  # first char
                [ -n "$unit" ] || return 1

                case "$unit" in
                    s) total=$(( total + n )) ;;
                    m) total=$(( total + n * 60 )) ;;
                    h) total=$(( total + n * 3600 )) ;;
                    d) total=$(( total + n * 86400 )) ;;
                    w) total=$(( total + n * 604800 )) ;;
                    *) return 1 ;;
                esac

                rest="${rest#$n_raw$unit}"
            done
            [ "$total" -gt 0 ] || return 1
            x_=$(( now - total ))
            return 0
            ;;
    esac

    # absolute time string: must contain a date/time separator
    case "$since" in
        *[-:/[:space:]]*) ;;
        *) return 1 ;;
    esac

    x_="$(___x_cmd date timestamp "$since" 2>/dev/null)" || return 1
}

___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 recent_dir="$1"
    local base_dir="$2"
    [ -d "$recent_dir" ] || return 0

    ___x_cmd_claw_log___output_all "$base_dir"

    { ___x_cmd_is_stdout2tty && ___x_cmd_runmode_allow_manual; } || return 0

    shift 2
    local x_="" l=""
    ___x_cmd fsiter --file_ "$recent_dir"
    while read -r l; do
        set -- "$@" "$recent_dir/$l"
    done <<A
$x_
A
    ___x_cmd_cmds tail -F -q -n 0 "$@" | CLAW_LOG_COLOR="$CLAW_LOG_COLOR" CLAW_LOG_DEBUG="$CLAW_LOG_DEBUG" ___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 base_dir="$1"
    [ -d "$base_dir" ] || return 0

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

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

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