# shellcheck shell=dash

___X_CMD_JINA_CACHE_TIME=10m

___X_CMD_JINA_CACHE_TIME_READER=1d

___x_cmd_jina_reader(){
    [ $# -gt 0 ] ||    set - --help

    local fmt=markdown
    local url=""
    local nocache=

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help)      ___x_cmd help -m jina reader;
                            return ;;

            --md)           fmt=markdown    ;;
            --html|--txt)
                            fmt="${1#--}"   ;;

            --imagecaption)
                            fmt=x-with-generated-alt
                            ;;

            --screenshot)
                            fmt=screenshot  ;;

            --nocache)      nocache=1       ;;

            *)              url="$1";
                            break       ;;
        esac
        shift
    done

    ___x_cmd_jina_reader___app
}

___x_cmd_jina_reader___app(){
    if ___x_cmd_is_stdout2tty && ___x_cmd_runmode_allow_manual; then
        case "$fmt" in
            markdown)              ___x_cmd_jina_reader___raw | ___x_cmd bat -l markdown ;;
            html)                  ___x_cmd_jina_reader___raw | ___x_cmd bat -l html ;;
            # json)                  ___x_cmd_jina_reader___raw | ___x_cmd bat -l json ;;
            txt)                   ___x_cmd_jina_reader___raw | ___x_cmd_cmds less ;;
            screenshot)            ___x_cmd_jina_reader___raw ;;
            x-with-generated-alt)  ___x_cmd_jina_reader___raw ;;
        esac
    else
        ___x_cmd_jina_reader___raw
    fi
}

___x_cmd_jina_reader___raw(){
    local apikey=
    local proxy=

    ___x_cmd_jina_cur     apikey:=     proxy:=     2>/dev/null
    set - ${proxy:+-x} ${proxy:+"$proxy"} ${apikey:+-H} ${apikey:+"\"Authorization: Bearer ${apikey}\""} -H "x-respond-with: $fmt"  -s "https://r.jina.ai/$url"

    if [ -z "$nocache" ]; then
        ___x_cmd ccmd   "$___X_CMD_JINA_CACHE_TIME_READER" \
            -- ___x_cmd_jina_reader_curl "$@"
    else
        ___x_cmd_jina_reader_curl "$@"
    fi
}

___x_cmd_jina_reader_curl(){
    if [ -z "$nocache" ]; then
        jina:debug "x curl $*"
        ___x_cmd curl "$@"
    else
        jina:debug "x curl -H 'x-no-cache: true' $*"
        ___x_cmd curl -H 'x-no-cache: true' "$@"
    fi
}
