export NOTE_PATH="$HOME/Sync/Nole"  # 设置笔记存储路径
export TEMPLATE_FILE="$NOTE_PATH/template.md"  # 设置模板文件路径
export NOTE_EDITOR="code"  # 设置默认编辑器为 vscode

# 用法：new_note filename
# 该函数在$NOTE_PATH目录下按照 {year}-{month}/{timestamp}-{random}/{filename}.md 创建新的笔记文件，并打开$NOTE_EDITOR
# 当前没有设置$NOTEPATH时，默认在当前目录下创建
# 当前没有设置$NOTE_EDITOR时，默认使用vi打开文件
# 如果设置了$TEMPLATE_FILE，则在创建文件时复制模板内容
# 依赖 ripgrep fzf bat

function _note_new() {
    local filename="$1"

    # 如果没有传入 filename，提示用户输入
    if [[ -z "$filename" ]]; then
        echo "Error: Filename must be specified."
        return 1
    fi

    local year_month=$(date +"%Y-%m")  # 获取当前年月，如 2025-04
    # 生成 秒级时间戳-四位16进制随机数
    local timestamp=$(printf "%d-%04x" $(date +%s) $((0x$(head -c 2 /dev/urandom | od -An -tx2 | tr -d ' '))))
    local dir_path="${NOTE_PATH:-.}/${year_month}/${timestamp}"
    local file_path="${dir_path}/${filename}.md"
    
    # 创建目录（如果不存在）
    mkdir -p "$dir_path"
    
    # 创建文件
    if [[ -n "$TEMPLATE_FILE" && -f "$TEMPLATE_FILE" ]]; then
        # 如果设置了模板文件且文件存在，则复制模板内容
        cp "$TEMPLATE_FILE" "$file_path"
    else
        # 否则创建空文件
        touch "$file_path"
    fi

    echo "Note created at: $file_path"
    
    # 使用 $Editor 打开文件（如果 $Editor 未设置，则使用默认编辑器）
    ${NOTE_EDITOR:-vi} "$file_path"
}

function _note_search() {
    local keyword="$1"

    if [[ -z "$keyword" ]]; then
        echo "Error: Search keywords must be specified."
        return 1
    fi

    # 1. 先用 rg 找出匹配的文件
    local files=$(rg --files-with-matches -i "$keyword" ${NOTE_PATH:-.} --type markdown)

    if [[ ${#files[@]} -eq 0 ]]; then
        echo "No matches found."
        return 1
    fi

    # 2. 检查是否安装了 fzf
    if command -v fzf &>/dev/null; then
        printf "%s\n" "${files[@]}" | fzf --reverse --preview "bat --color=always --language markdown --style=plain {} | rg --color=always -i \"$keyword\" -C 5" --preview-window=right:60%:wrap --delimiter=/ --with-nth=-3,-1 --bind 'enter:become(${NOTE_EDITOR:-vi} {})'
    else
        # 没有 fzf，直接列出所有匹配的文件路径
        echo "Found ${#files[@]} matching files (install fzf for interactive selection):"
        printf "  - %s\n" "${files[@]}"
    fi
}

function _note_list() {

    if command -v fzf &>/dev/null; then
        find "${NOTE_PATH:-.}" -name "*.md" | fzf --height 100% --reverse --preview 'bat --color=always --language markdown --style=plain {}' --preview-window=right:60%:wrap --delimiter=/ --with-nth=-3,-1 --bind 'enter:become(${NOTE_EDITOR:-vi} {})'
    else
        # 如果没有安装 fzf，直接列出所有文件
        echo "Listing all notes (install fzf for interactive selection):"
        find "${NOTE_PATH:-.}" -name "*.md" | while read -r file; do
            echo "  - $file"
        done
    fi
}

# nole 精灵语 知识
function nole() {
    if [[ $# -eq 0 ]]; then
        echo "Usage: nole {new|search|list} [args]"
        echo "Commands:"
        echo "  new <filename>    Create a new note, n"
        echo "  search <keyword>  Search notes by keyword, s"
        echo "  list              List all notes, ls"
        return 1
    fi

    local command="$1"
    shift  # 移除命令名，剩下的参数传递给子命令

    case "$command" in
        new)
            _note_new "$@"
            ;;
        n)
            _note_new "$@"
            ;;
        search)
            _note_search "$@"
            ;;
        s)
            _note_search "$@"
            ;;
        list)
            _note_list "$@"
            ;;
        ls)
            _note_list "$@"
            ;;
        *)
            echo "Error: Unknown command '$command'"
            echo "Usage: note {new|search|list} [args]"
            return 1
            ;;
    esac
}
