#!/usr/bin/env bash
# rseek — Ruggi Seek: find your files by words AND by meaning.
#
#   rseek "question or words" [--in DIR] [--words|--meaning|--both] [--limit N] [--open N]
#   rseek index      read the folders you chose; only changed files are read again
#   rseek status     what is indexed, and whether meaning search is ready
#   rseek config     show the settings;  rseek config add DIR | remove DIR | set KEY VALUE | edit
#   rseek gui        the results window
#
# How it works, in short:
#   - every file is cut into overlapping pieces ("chunks") kept in ONE SQLite database;
#   - word search is SQLite's FTS5 index over those pieces;
#   - meaning search compares the question's embedding vector with one stored vector per piece
#     (vectors come from a local Ollama server; nothing leaves this computer);
#   - the two rankings are merged with Reciprocal Rank Fusion (k = 60).
# Word search never needs Ollama. When Ollama or the model is missing, rseek says so in one short
# note and carries on with words.
#
# bash + sqlite3 + curl + jq. pdftotext (poppler-utils) for PDFs, unzip for odt/docx.

set -u
VERSION=1.0.1

# ---------- where things live ----------
SELF=$(readlink -f "${BASH_SOURCE[0]}")
HERE=$(dirname "$SELF")
CONF_DIR=${RSEEK_CONFIG_DIR:-${XDG_CONFIG_HOME:-$HOME/.config}/ruggi-seek}
DATA_DIR=${RSEEK_DATA_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/ruggi-seek}
CONF=$CONF_DIR/config
DB=$DATA_DIR/index.sqlite

# the library sits next to the source tree's bin/, or under the data folder once installed
for d in "${RSEEK_LIB:-}" "$HERE/../lib" "${XDG_DATA_HOME:-$HOME/.local/share}/ruggi-seek/lib"; do
    [ -n "$d" ] && [ -f "$d/embed.sh" ] && { LIB=$d; break; }
done
[ -n "${LIB:-}" ] || { echo "rseek: lib/embed.sh not found (reinstall Ruggi Seek)" >&2; exit 1; }
. "$LIB/embed.sh"

# the optional fast vector helper: next to rseek, or built in the source tree
if [ -z "${RSEEK_VEC+x}" ]; then
    RSEEK_VEC=
    for f in "$HERE/rseek-vec" "$HERE/../gui/bin/rseek-vec"; do [ -x "$f" ] && { RSEEK_VEC=$f; break; }; done
fi

TAB=$'\t'
say()  { printf '%s\n' "$*"; }
note() { printf 'note: %s\n' "$*" >&2; }
die()  { printf 'rseek: %s\n' "$*" >&2; exit 1; }
sql()  { emb_sql "$@"; }
q()    { emb_q "$1"; }

# ---------- settings ----------
# One plain file: "key = value" lines. "folder" may appear many times, the others once.
DEFAULT_CONFIG='# Ruggi Seek settings. Lines are  key = value ; a line starting with # is a comment.
# Change them here, or with:  rseek config add DIR | remove DIR | set KEY VALUE

# Folders to index: one "folder" line each.
#folder = ~/Documents

# Meaning search (a local Ollama server). "meaning = off" keeps Ruggi Seek to word search.
meaning = on
embed_url = http://127.0.0.1:11434/api/embed
# The embedding model. "auto" goes by the languages of this computer: embed_model_en when
# everything is English, embed_model_multi otherwise (it understands many languages, and a
# question in one finds text in another). Or put one model name here to use it always.
embed_model = auto
embed_model_en = nomic-embed-text
embed_model_multi = bge-m3

# What a plain  rseek "..."  searches with: both, words or meaning.
mode = both
# How many results to show.
limit = 20
# A piece must be at least this similar (0 to 1) to count as a meaning match.
# "auto" goes by the model: 0.55 for nomic-embed-text, 0.50 for bge-m3 and others.
min_score = auto

# Index folders whose name starts with a dot (yes / no).
hidden = no
# Largest text file read, in KB, and largest PDF or office document, in MB.
max_file_kb = 1024
max_doc_mb = 64
# Extra file endings to read as plain text, and extra folder names to skip (space separated).
extensions =
skip_folders =
'

cfg_get() {   # <key> <default>: the last value of a key
    local v=
    [ -f "$CONF" ] && v=$(sed -n "s/^[[:space:]]*$1[[:space:]]*=[[:space:]]*//p" "$CONF" | tail -n 1 | sed 's/[[:space:]]*$//')
    printf '%s' "${v:-$2}"
}

expand_dir() {   # ~ and relative paths to an absolute path without a trailing slash
    local p=$1
    case $p in "~") p=$HOME;; "~/"*) p=$HOME/${p#"~/"};; esac
    if [ -d "$p" ]; then (cd "$p" && pwd -P); else
        case $p in /*) ;; *) p=$PWD/$p;; esac
        printf '%s\n' "${p%/}"
    fi
}

cfg_folders() {   # one absolute folder per line
    [ -f "$CONF" ] || return 0
    sed -n 's/^[[:space:]]*folder[[:space:]]*=[[:space:]]*//p' "$CONF" | sed 's/[[:space:]]*$//' |
    while IFS= read -r f; do [ -n "$f" ] && expand_dir "$f"; done
}

# ---------- which embedding model ----------
# "embed_model = auto" goes by the languages of this computer: embed_model_en when everything is
# English, embed_model_multi otherwise (another language, several, or nothing known: the
# multilingual model reads English too, so it is the safe one).
# The pick is remembered in the data folder, so the window, the terminal and the timer (whose
# environment has no language settings) all use the same model and nothing is embedded twice.
# "rseek config set embed_model ..." forgets it; the next run picks again.
LANG_FILE="$DATA_DIR/embed.lang"

os_lang() {   # prints "english" or "multi", from LANG, LANGUAGE and every LC_* of the environment
    env | sed -n 's/^\(LANG\|LANGUAGE\|LC_[A-Z_]*\)=//p' | tr ':' '\n' | tr 'A-Z' 'a-z' | sed 's/[.@].*//' | awk '
        $0 == "" || $0 == "c" || $0 == "posix" { next }
        $0 == "en" || $0 ~ /^en_/ { en = 1; next }
        { other = 1 }
        END { print (en && !other) ? "english" : "multi" }'
}

pick_model() {   # the model to use: the setting, or with "auto" the one for this computer
    local m l
    m=$(cfg_get embed_model auto)
    if [ "$m" = auto ]; then
        l=$(cat "$LANG_FILE" 2>/dev/null)
        case $l in english|multi) ;; *) l=$(os_lang); mkdir -p "$DATA_DIR" 2>/dev/null; printf '%s\n' "$l" > "$LANG_FILE" 2>/dev/null;; esac
        if [ "$l" = english ]; then m=$(cfg_get embed_model_en nomic-embed-text); else m=$(cfg_get embed_model_multi bge-m3); fi
    fi
    printf '%s' "$m"
}

# Similarity numbers differ from model to model, so "min_score = auto" goes by the model:
# measured 2026-12 on short texts, nomic-embed-text 0.55, bge-m3 0.50; 0.50 for other models.
pick_min_score() {   # <model>
    local s; s=$(cfg_get min_score auto)
    case $s in
        auto|''|*[!0-9.]*) case $1 in nomic-embed-text*) s=0.55;; *) s=0.50;; esac;;
    esac
    printf '%s' "$s"
}

cfg_init() {
    mkdir -p "$CONF_DIR" "$DATA_DIR"
    [ -f "$CONF" ] || printf '%s' "$DEFAULT_CONFIG" > "$CONF"
}

load_settings() {
    MEANING=$(cfg_get meaning on)
    EMB_URL=${RSEEK_EMBED_URL:-$(cfg_get embed_url http://127.0.0.1:11434/api/embed)}
    EMB_MODEL=${RSEEK_EMBED_MODEL:-$(pick_model)}
    MODE=$(cfg_get mode both)
    LIMIT=$(cfg_get limit 20)
    MIN_SCORE=$(pick_min_score "$EMB_MODEL")
    HIDDEN=$(cfg_get hidden no)
    MAX_FILE_KB=$(cfg_get max_file_kb 1024)
    MAX_DOC_MB=$(cfg_get max_doc_mb 64)
    EXTRA_EXT=$(cfg_get extensions "")
    EXTRA_SKIP=$(cfg_get skip_folders "")
    case $LIMIT in ''|*[!0-9]*) LIMIT=20;; esac
    case $MAX_FILE_KB in ''|*[!0-9]*) MAX_FILE_KB=1024;; esac
    case $MAX_DOC_MB in ''|*[!0-9]*) MAX_DOC_MB=64;; esac
}

# ---------- the database ----------
# files   one row per file seen (size + mtime tell a changed file without reading it; hash is the
#         hash of the extracted text, so a touched but unchanged file costs nothing more)
# chunks  the overlapping pieces of each file; title = the file name
# chunks_fts  the word index over chunks (FTS5, kept in step by triggers)
# emb_vecs    one vector per piece of text and model (see lib/embed.sh)
CHUNK=1500        # characters in one piece
OVERLAP=200       # characters two neighbours share
TEXT_CAP_KB=512   # extracted text kept per file (the start of a huge file is what gets indexed)

db_init() {
    mkdir -p "$DATA_DIR"
    sql "$DB" "
        PRAGMA journal_mode = WAL;
        CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT);
        CREATE TABLE IF NOT EXISTS files(
            id INTEGER PRIMARY KEY, path TEXT UNIQUE, name TEXT, size INTEGER, mtime INTEGER,
            hash TEXT, kind TEXT, indexed_at INTEGER);
        CREATE TABLE IF NOT EXISTS chunks(
            id INTEGER PRIMARY KEY, file_id INTEGER, seq INTEGER, hash TEXT, title TEXT, body TEXT);
        CREATE INDEX IF NOT EXISTS chunks_file ON chunks(file_id);
        CREATE INDEX IF NOT EXISTS chunks_hash ON chunks(hash);
        CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
            title, body, content='chunks', content_rowid='id', tokenize='unicode61 remove_diacritics 2');
        CREATE TRIGGER IF NOT EXISTS chunks_ai AFTER INSERT ON chunks BEGIN
            INSERT INTO chunks_fts(rowid, title, body) VALUES (new.id, new.title, new.body); END;
        CREATE TRIGGER IF NOT EXISTS chunks_ad AFTER DELETE ON chunks BEGIN
            INSERT INTO chunks_fts(chunks_fts, rowid, title, body) VALUES ('delete', old.id, old.title, old.body); END;
        CREATE TRIGGER IF NOT EXISTS files_ad AFTER DELETE ON files BEGIN
            DELETE FROM chunks WHERE file_id = old.id; END;
        CREATE TABLE IF NOT EXISTS emb_vecs(hash TEXT, model TEXT, vec TEXT, PRIMARY KEY(hash, model));
    " >/dev/null || die "cannot open the index at $DB"
}

db_need() { [ -f "$DB" ] || die "nothing is indexed yet. Choose a folder and index it:
    rseek config add ~/Documents
    rseek index"; }

# SQL condition "this file is inside DIR" (on files f). A range on the path, so the UNIQUE index
# on path answers it: '0' is the character right after '/'.
in_cond() { printf "(f.path >= %s AND f.path < %s)" "$(q "$1/")" "$(q "${1}0")"; }

# ---------- reading files ----------
# Folder names never entered: version control, package and build caches, trash.
SKIP_DIRS=".git .svn .hg node_modules bower_components .cache cache Cache CacheStorage __pycache__
.venv venv .tox .npm .cargo .gradle .m2 .mypy_cache .pytest_cache .Trash .Trash-1000 Trash
.thumbnails lost+found"

# File endings read as plain text. Everything not listed here (and not html / pdf / office below)
# is left alone: disk images, ISOs, archives, pictures, audio, video, programs.
TEXT_EXT="txt md markdown rst org tex bib log csv tsv json jsonl yaml yml toml ini conf cfg cnf
properties env xml svg css scss less js mjs cjs ts jsx tsx vue php phtml py rb pl pm sh bash zsh
fish ps1 bat cmd c h cc cpp cxx hpp hh java kt kts scala go rs swift m mm cs vb bas cls frm pas pp
lpr lfm dpr inc lua sql r jl hs ml clj ex exs erl dart asm s nim zig tcl awk sed vim el lisp scm
srt vtt sub ass desktop service timer rules nemo_action diff patch gradle cmake mk make dockerfile
htaccess gitignore editorconfig nfo txt2 text adoc asciidoc wiki rtf tf proto graphql"

# stdin: "path<TAB>size<TAB>mtime" from find. stdout: "path<TAB>size<TAB>mtime<TAB>kind" for the
# files worth reading. kind: text, html, pdf, odf, docx, or maybe (no ending: looked at later).
classify() {
    awk -F'\t' -v text="$TEXT_EXT $EXTRA_EXT" -v maxkb="$MAX_FILE_KB" -v maxmb="$MAX_DOC_MB" '
        BEGIN { n = split(text, a, /[ \n]+/); for (i = 1; i <= n; i++) if (a[i] != "") istext[a[i]] = 1 }
        {
            path = $1; size = $2 + 0
            name = path; sub(/.*\//, "", name)
            low = tolower(name)
            # generated or machine-made text: long, and never what you are looking for
            if (low ~ /\.min\.(js|css)$/ || low ~ /\.map$/ || low ~ /(^|-)lock\.(json|yaml)$/ || low ~ /\.lock$/) next
            ext = ""
            if (low ~ /\./) { ext = low; sub(/.*\./, "", ext) }
            kind = ""
            if (ext == "") kind = "maybe"
            else if (ext == "html" || ext == "htm" || ext == "xhtml") kind = "html"
            else if (ext == "pdf") kind = "pdf"
            else if (ext == "odt" || ext == "ods" || ext == "odp") kind = "odf"
            else if (ext == "docx") kind = "docx"
            else if (ext in istext) kind = "text"
            if (kind == "") next
            if (kind == "pdf" || kind == "odf" || kind == "docx") { if (size > maxmb * 1048576) next }
            else if (size > maxkb * 1024) next
            printf "%s\t%d\t%d\t%s\n", path, size, $3, kind
        }'
}

# XML or HTML on stdin to plain text: block ends become line breaks, tags go, common entities come back.
xml_to_text() {
    tr '\n\r' '  ' |
    sed -E 's/<(script|style)[^>]*>/\n\x01/Ig; s/<\/(script|style)>/\n/Ig' | grep -v $'^\x01' | tr '\n' ' ' |
    sed -E 's/<\/(p|div|h[1-6]|li|tr|table|title|text:p|text:h|w:p)>|<br[^>]*>|<text:line-break\/>/\n/Ig
            s/<[^>]*>/ /g
            s/&nbsp;/ /g; s/&lt;/</g; s/&gt;/>/g; s/&quot;/"/g; s/&#39;/'"'"'/g; s/&apos;/'"'"'/g; s/&amp;/\&/g
            s/[ \t]+/ /g; s/^ //; s/ $//' | grep -v '^$'
}

# Write the text of one file to <out>. Returns:
#   0  text written (possibly none: a scanned PDF is still found by its name)
#   1  not a text file at all (a program with no file ending): remembered as "skip", never read again
#   2  the tool that reads this kind is not installed: found by name only, read once the tool is there
extract() {   # <kind> <path> <out>
    local cap=$((TEXT_CAP_KB * 1024))
    case $1 in
        maybe) grep -Iq . "$2" 2>/dev/null || return 1;;
        pdf)   [ "$HAVE_PDF" = 1 ] || { : > "$3"; return 2; };;
        odf|docx) [ "$HAVE_UNZIP" = 1 ] || { : > "$3"; return 2; };;
    esac
    case $1 in
        text|maybe) head -c "$cap" "$2";;
        html)  xml_to_text < "$2";;
        pdf)   timeout 120 pdftotext -q -enc UTF-8 "$2" - 2>/dev/null;;
        odf)   unzip -p "$2" content.xml 2>/dev/null | xml_to_text;;
        docx)  unzip -p "$2" word/document.xml 2>/dev/null | xml_to_text;;
    esac | head -c "$cap" | tr -d '\000' | iconv -f UTF-8 -t UTF-8 -c 2>/dev/null > "$3"
    return 0
}

# ---------- rseek index ----------
cmd_index() {
    local quiet=0 no_meaning=0 rebuild=0 a
    for a in "$@"; do
        case $a in
            --quiet|-q) quiet=1;;
            --no-meaning|--words) no_meaning=1;;
            --rebuild) rebuild=1;;
            *) die "index: unknown option $a";;
        esac
    done
    cfg_init; load_settings
    emb_tools || die "sqlite3 (3.38 or newer), jq and curl are needed. Run install.sh, it offers to install them."
    local folders; folders=$(cfg_folders)
    [ -n "$folders" ] || die "no folders to index yet. Add one:
    rseek config add ~/Documents"

    # one index run at a time (the timer and a run by hand must not overlap)
    mkdir -p "$DATA_DIR"
    exec 9> "$DATA_DIR/index.lock"
    flock -n 9 || die "another rseek index is running"
    [ "$rebuild" = 1 ] && rm -f "$DB" "$DB-wal" "$DB-shm"
    db_init

    HAVE_PDF=0; command -v pdftotext >/dev/null 2>&1 && HAVE_PDF=1
    HAVE_UNZIP=0; command -v unzip >/dev/null 2>&1 && HAVE_UNZIP=1
    ITMP=$(mktemp -d) || die "no temporary folder"; local tmp=$ITMP
    trap 'rm -rf "$ITMP"' EXIT

    # 1. list the files (names, sizes, times: nothing is read yet)
    local prune=() d first=1 missing_cond=""
    for d in $SKIP_DIRS $EXTRA_SKIP; do
        [ "$first" = 1 ] && first=0 || prune+=(-o)
        prune+=(-name "$d")
    done
    [ "$HIDDEN" = yes ] || prune+=(-o -name '.?*')
    : > "$tmp/found"
    while IFS= read -r d; do
        if [ ! -d "$d" ]; then
            # an unplugged drive must not wipe its files from the index: keep them, say so
            note "folder not found, kept as it was: $d"
            missing_cond="$missing_cond AND NOT (path >= $(q "$d/") AND path < $(q "${d}0"))"
            continue
        fi
        [ "$quiet" = 1 ] || say "reading the file list of $d"
        find "$d" -mindepth 1 \( -type d \( "${prune[@]}" \) -prune \) -o \
             -type f ! -name $'*\n*' ! -name $'*\t*' ! -path $'*\n*' ! -path $'*\t*' \
             -printf '%p\t%s\t%T@\n' 2>/dev/null |
        awk -v quiet="$quiet" '
            { print }
            # a big folder is listed for minutes: say that it is moving (the window shows this line)
            !quiet && NR % 5000 == 0 { printf "\r  listing files: %d so far", NR > "/dev/stderr" }
            END { if (!quiet && NR >= 5000) printf "\r  listing files: %d\n", NR > "/dev/stderr" }' >> "$tmp/found"
    done <<< "$folders"
    classify < "$tmp/found" | sort -u -t "$TAB" -k1,1 > "$tmp/seen"
    [ "$HAVE_PDF" = 0 ] && grep -q "${TAB}pdf\$" "$tmp/seen" && note "pdftotext is not installed: PDFs are found by name only (package poppler-utils)"
    true

    # 2. compare with the index: forget files that are gone, list the new and changed ones (and
    #    the documents that could not be read before because their tool was missing)
    local removed readable="''"
    [ "$HAVE_PDF" = 1 ] && readable="$readable, 'pdf'"
    [ "$HAVE_UNZIP" = 1 ] && readable="$readable, 'odf', 'docx'"
    removed=$(sql "$DB" <<EOF
DROP TABLE IF EXISTS seen;
CREATE TABLE seen(path TEXT PRIMARY KEY, size INTEGER, mtime INTEGER, kind TEXT);
.mode ascii
.separator "\t" "\n"
.import '$tmp/seen' seen
.mode list
BEGIN;
SELECT count(*) FROM files WHERE path NOT IN (SELECT path FROM seen) $missing_cond;
DELETE FROM files WHERE path NOT IN (SELECT path FROM seen) $missing_cond;
COMMIT;
.separator "\t" "\n"
.output '$tmp/todo'
SELECT s.path, s.size, s.mtime, s.kind FROM seen s LEFT JOIN files f ON f.path = s.path
WHERE f.id IS NULL OR f.size <> s.size OR f.mtime <> s.mtime
   OR (f.kind = 'noread' AND s.kind IN ($readable)) ORDER BY s.path;
.output stdout
DROP TABLE seen;
EOF
    ) || die "the index could not be updated"
    local total; total=$(wc -l < "$tmp/todo")

    # 3. read the new and changed files, a batch at a time: extract the text of each into a
    #    temporary file, then one sqlite3 call cuts the whole batch into pieces
    local n=0 batch=0 changed=0 same=0 path size mtime kind step=$((CHUNK - OVERLAP)) out
    local maxn=$(( TEXT_CAP_KB * 1024 / step + 2 ))
    index_flush() {
        [ -s "$tmp/batch.sql" ] || return 0
        out=$(sql "$DB" <<EOF
CREATE TEMP TABLE stage(path TEXT PRIMARY KEY, size INTEGER, mtime INTEGER, kind TEXT, body TEXT, hash TEXT);
.read '$tmp/batch.sql'
UPDATE stage SET hash = CASE WHEN kind = 'skip' THEN '' ELSE lower(hex(sha3(body))) END;
BEGIN;
-- same text as last time (the file was only touched or saved unchanged): note the new time, done
CREATE TEMP TABLE same AS SELECT s.path FROM stage s JOIN files f ON f.path = s.path AND f.hash = s.hash AND f.kind = s.kind;
UPDATE files SET size = s.size, mtime = s.mtime FROM stage s WHERE files.path = s.path AND files.path IN (SELECT path FROM same);
DELETE FROM stage WHERE path IN (SELECT path FROM same);
-- new text: drop the old pieces, write the new ones (the triggers keep the word index in step)
DELETE FROM chunks WHERE file_id IN (SELECT f.id FROM files f JOIN stage s ON s.path = f.path);
INSERT INTO files(path, name, size, mtime, hash, kind, indexed_at)
    SELECT path, replace(path, rtrim(path, replace(path, '/', '')), ''), size, mtime, hash, kind, strftime('%s', 'now') FROM stage WHERE true
    ON CONFLICT(path) DO UPDATE SET size = excluded.size, mtime = excluded.mtime, hash = excluded.hash,
                                    kind = excluded.kind, indexed_at = excluded.indexed_at;
WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM n WHERE i + 1 < $maxn),
pieces AS (SELECT f.id AS file_id, n.i AS seq, f.name AS title, substr(s.body, n.i * $step + 1, $CHUNK) AS body
           FROM stage s JOIN files f ON f.path = s.path
           JOIN n ON n.i = 0 OR length(s.body) > n.i * $step + $OVERLAP
           WHERE s.kind <> 'skip')
INSERT INTO chunks(file_id, seq, hash, title, body)
    SELECT file_id, seq, lower(hex(sha3(title || char(10) || body))), title, body FROM pieces ORDER BY file_id, seq;
SELECT (SELECT count(*) FROM stage) || ' ' || (SELECT count(*) FROM same);
COMMIT;
EOF
        ) || die "the index could not be updated"
        changed=$((changed + ${out% *})); same=$((same + ${out#* }))
        : > "$tmp/batch.sql"; rm -f "$tmp"/t.*; batch=0
    }
    : > "$tmp/batch.sql"
    while IFS="$TAB" read -r path size mtime kind; do
        n=$((n + 1)); batch=$((batch + 1))
        extract "$kind" "$path" "$tmp/t.$batch"
        case $? in
            0) ;;
            1) kind=skip;;
            *) kind=noread;;
        esac
        if [ "$kind" = skip ]; then
            printf "INSERT OR REPLACE INTO stage(path, size, mtime, kind, body) VALUES (%s, %d, %d, 'skip', '');\n" \
                "$(q "$path")" "$size" "$mtime" >> "$tmp/batch.sql"
        else
            printf "INSERT OR REPLACE INTO stage(path, size, mtime, kind, body) VALUES (%s, %d, %d, '%s', CAST(readfile('%s') AS TEXT));\n" \
                "$(q "$path")" "$size" "$mtime" "$kind" "$tmp/t.$batch" >> "$tmp/batch.sql"
        fi
        if [ "$batch" -ge 200 ]; then
            index_flush
            [ "$quiet" = 1 ] || printf '\r  read %d of %d files' "$n" "$total" >&2
        fi
    done < "$tmp/todo"
    index_flush
    [ "$quiet" = 1 ] || { [ "$total" -ge 200 ] && printf '\r  read %d of %d files\n' "$n" "$total" >&2; }
    sql "$DB" "INSERT OR REPLACE INTO meta VALUES ('indexed_at', strftime('%s', 'now'));"
    say "files: $changed indexed, $same same content, $removed removed"

    # 4. vectors for the pieces that have none yet (only new text is ever sent to the model)
    emb_prune "$DB"
    if [ "$no_meaning" = 1 ] || [ "$MEANING" = off ]; then
        say "meaning: off"
    else
        local missing; missing=$(emb_missing "$DB" "$EMB_MODEL")
        if [ "${missing:-0}" = 0 ]; then
            say "meaning: 0 new vectors"
        elif emb_ready "$EMB_URL" "$EMB_MODEL"; then
            local done_n
            [ "$quiet" = 1 ] || EMB_PROGRESS=1
            done_n=$(EMB_PROGRESS=${EMB_PROGRESS:-0} emb_fill "$DB" "$EMB_URL" "$EMB_MODEL") ||
                note "the embedding server stopped answering; the rest is done at the next index"
            say "meaning: $done_n new vectors"
        else
            say "meaning: 0 new vectors"
            note "meaning search is not ready (no answer from Ollama for model $EMB_MODEL). Word search works."
        fi
    fi
    return 0
}

# ---------- rseek "query" ----------
# The words of a question as an FTS5 query. Every word is quoted (so no character can be read as
# FTS syntax) and matches as a prefix when it has 3 characters or more: "invoic" finds "invoices"
# in any language, with no language-specific stemming. "quoted phrases" stay phrases.
# $2 is the joiner: " " (all words) or " OR " (any word).
fts_query() {
    local text=$1 join=$2 out="" word="" inq=0 i ch
    add() {
        [ -n "$word" ] || return 0
        local w=${word//\"/}
        [ -n "$w" ] || { word=""; return 0; }
        if [ "$1" = phrase ] || [ "${#w}" -lt 3 ]; then w="\"$w\""; else w="\"$w\"*"; fi
        out="${out:+$out$join}$w"; word=""
    }
    for ((i = 0; i < ${#text}; i++)); do
        ch=${text:i:1}
        if [ "$ch" = '"' ]; then
            if [ "$inq" = 1 ]; then add phrase; inq=0; else add word; inq=1; fi
        elif [ "$inq" = 0 ] && [[ $ch == [[:space:]] ]]; then add word
        else word+=$ch
        fi
    done
    [ "$inq" = 1 ] && add phrase || add word
    printf '%s' "$out"
}

# Word ranking: "file id<TAB>path<TAB>snippet", best file first. A file ranks as its best piece;
# a match in the file name counts four times a match in the text. \x01 and \x02 mark the match.
search_words() {   # <query> <pool> <cond>
    local match join
    for join in " " " OR "; do
        match=$(fts_query "$1" "$join")
        [ -n "$match" ] || return 0
        sql -separator "$TAB" "$DB" "
            WITH hits AS (
                SELECT c.file_id AS fid, bm25(chunks_fts, 4.0, 1.0) AS r,
                       snippet(chunks_fts, 1, char(1), char(2), '…', 24) AS sn
                FROM chunks_fts JOIN chunks c ON c.id = chunks_fts.rowid JOIN files f ON f.id = c.file_id
                WHERE chunks_fts MATCH $(q "$match") AND $3
                ORDER BY r LIMIT 3000),
            best AS (SELECT fid, min(r) AS r, sn FROM hits GROUP BY fid)
            SELECT b.fid, f.path, replace(replace(replace(b.sn, char(10), ' '), char(13), ' '), char(9), ' ')
            FROM best b JOIN files f ON f.id = b.fid ORDER BY b.r, f.path LIMIT $2;" 2>/dev/null > "$STMP/w"
        [ -s "$STMP/w" ] && break     # nothing has ALL the words: accept ANY of them
    done
    return 0
}

# Meaning ranking: "file id<TAB>path<TAB>snippet<TAB>score", best file first. Returns 1 (and writes
# why in $MEANING_WHY) when meaning search cannot run.
search_meaning() {   # <query> <pool> <cond>
    MEANING_WHY=
    : > "$STMP/m"
    [ "$MEANING" = off ] && { MEANING_WHY="meaning search is switched off in the settings"; return 1; }
    local have; have=$(sql "$DB" "SELECT count(*) FROM emb_vecs WHERE model = $(q "$EMB_MODEL");" 2>/dev/null)
    [ "${have:-0}" -gt 0 ] || { MEANING_WHY="no meaning index yet (start Ollama with model $EMB_MODEL, then: rseek index)"; return 1; }
    local vec
    vec=$(EMB_TIMEOUT=${RSEEK_QUERY_TIMEOUT:-30} emb_query_vec "$EMB_URL" "$EMB_MODEL" "$1") ||
        { MEANING_WHY="Ollama or model $EMB_MODEL is not answering"; return 1; }
    emb_rank "$DB" "$EMB_MODEL" "$vec" $(( $2 * 5 )) "$MIN_SCORE" "$3" > "$STMP/mc"
    [ -s "$STMP/mc" ] || return 0
    # chunk scores to files: a file scores as its best piece, whose start becomes the snippet
    local values; values=$(awk -F'\t' '{ printf "%s(%d,%s)", (NR > 1 ? "," : ""), $1, $2 }' "$STMP/mc")
    sql -separator "$TAB" "$DB" "
        WITH m(cid, s) AS (VALUES $values),
        best AS (SELECT c.file_id AS fid, max(m.s) AS s, c.body AS body FROM m JOIN chunks c ON c.id = m.cid GROUP BY c.file_id)
        SELECT b.fid, f.path,
               trim(replace(replace(replace(substr(b.body, 1, 200), char(10), ' '), char(13), ' '), char(9), ' ')) || '…',
               printf('%.2f', b.s)
        FROM best b JOIN files f ON f.id = b.fid ORDER BY b.s DESC, f.path LIMIT $2;" > "$STMP/m"
    return 0
}

cmd_search() {
    local query="" in_dir="" mode="" limit="" open_n="" format=human
    while [ $# -gt 0 ]; do
        case $1 in
            --in)       [ $# -ge 2 ] || die "--in needs a folder"; in_dir=$2; shift;;
            --in=*)     in_dir=${1#--in=};;
            --words|-w) mode=words;;
            --meaning|-m) mode=meaning;;
            --both|-b)  mode=both;;
            --limit|-n) [ $# -ge 2 ] || die "--limit needs a number"; limit=$2; shift;;
            --limit=*)  limit=${1#--limit=};;
            --open|-o)  [ $# -ge 2 ] || die "--open needs a result number"; open_n=$2; shift;;
            --open=*)   open_n=${1#--open=};;
            --tsv)      format=tsv;;
            --json)     format=json;;
            --)         shift; query="${query:+$query }$*"; break;;
            -*)         die "unknown option $1 (see: rseek help)";;
            *)          query="${query:+$query }$1";;
        esac
        shift
    done
    [ -n "$query" ] || die "what should I look for?  rseek \"words or a question\""
    load_settings; db_need
    mode=${mode:-$MODE}; limit=${limit:-$LIMIT}
    case $limit in ''|*[!0-9]*) die "--limit needs a number";; esac
    case $open_n in *[!0-9]*) die "--open needs a result number";; esac
    local cond=1
    if [ -n "$in_dir" ]; then in_dir=$(expand_dir "$in_dir"); cond=$(in_cond "$in_dir"); fi

    STMP=$(mktemp -d) || die "no temporary folder"
    trap 'rm -rf "$STMP"' EXIT
    : > "$STMP/w"; : > "$STMP/m"
    local pool=$(( limit > 50 ? limit : 50 ))      # each ranking brings its best 50 files to the merge

    [ "$mode" = meaning ] || search_words "$query" "$pool" "$cond"
    if [ "$mode" != words ]; then
        if ! search_meaning "$query" "$pool" "$cond"; then
            # the one short note; with --meaning there is nothing else to show, so fall back to words
            note "$MEANING_WHY; showing word matches"
            [ "$mode" = meaning ] && search_words "$query" "$pool" "$cond"
        fi
    fi

    # merge: "list<TAB>file id" lines, each list best first, through Reciprocal Rank Fusion; then
    # put path, why-found marker and snippet next to every id. A word snippet (it shows the match)
    # wins over a meaning snippet.
    {   awk -F'\t' '{ print "words\t" $1 }' "$STMP/w"
        awk -F'\t' '{ print "meaning\t" $1 }' "$STMP/m"
    } | rrf_merge 60 | head -n "$limit" |
    awk -F'\t' -v wf="$STMP/w" -v mf="$STMP/m" '
        BEGIN {
            while ((getline line < wf) > 0) { split(line, a, "\t"); path[a[1]] = a[2]; snip[a[1]] = a[3] }
            while ((getline line < mf) > 0) {
                split(line, a, "\t"); path[a[1]] = a[2]; sim[a[1]] = a[4]
                if (!(a[1] in snip)) snip[a[1]] = a[3]
            }
        }
        { s = snip[$1]; gsub(/  +/, " ", s); printf "%s\t%s\t%s\t%s\t%s\n", path[$1], $3, $2, (($1 in sim) ? sim[$1] : ""), s }' > "$STMP/out"
    # columns of out: path, why (words | meaning | words+meaning), fused score, cosine, snippet

    case $format in
        tsv)  cat "$STMP/out";;
        json) jq -R -s '[split("\n")[] | select(length > 0) | split("\t")
                         | {path: .[0], why: .[1], score: (.[2] | tonumber),
                            similarity: (if .[3] == "" then null else (.[3] | tonumber) end),
                            snippet: (.[4] | gsub("[\u0001\u0002]"; ""))}]' "$STMP/out";;
        *)    print_human "$STMP/out" "$query";;
    esac

    if [ -n "$open_n" ]; then
        local target; target=$(sed -n "${open_n}p" "$STMP/out" | cut -f1)
        [ -n "$target" ] || die "there is no result number $open_n"
        say "opening $target"
        setsid xdg-open "$target" >/dev/null 2>&1 &
    fi
    return 0
}

# Results for people. The why-found marker is a word in brackets, never a colour alone; in a
# terminal the matched words are also bold.
print_human() {   # <out file> <query>
    local b="" e="" dim="" off=""
    if [ -t 1 ]; then b=$'\033[1m'; e=$'\033[22m'; dim=$'\033[2m'; off=$'\033[0m'; fi
    if [ ! -s "$1" ]; then say "nothing found for: $2"; return 0; fi
    awk -F'\t' -v home="$HOME" -v b="$b" -v e="$e" -v dim="$dim" -v off="$off" '
        {
            p = $1; if (index(p, home "/") == 1) p = "~" substr(p, length(home) + 1)
            why = $2; if ($4 != "") why = why " " $4
            s = $5; gsub(/\001/, b, s); gsub(/\002/, e, s)
            printf "%2d. %s%s%s  %s[%s]%s\n", NR, b, p, e, dim, why, off
            if (s != "") printf "    %s\n", s
        }' "$1"
}

# ---------- rseek status ----------
cmd_status() {
    cfg_init; load_settings
    say "Ruggi Seek $VERSION"
    say "settings: $CONF"
    say "index:    $DB"
    local folders; folders=$(cfg_folders)
    if [ -n "$folders" ]; then
        say "folders:"
        while IFS= read -r d; do
            if [ -d "$d" ]; then say "  $d"; else say "  $d  (not found)"; fi
        done <<< "$folders"
    else
        say "folders:  none yet (rseek config add ~/Documents)"
    fi
    if [ -f "$DB" ]; then
        local row
        row=$(sql -separator "$TAB" "$DB" "
            SELECT (SELECT count(*) FROM files WHERE kind <> 'skip'), (SELECT count(*) FROM chunks),
                   (SELECT count(*) FROM chunks c WHERE EXISTS (SELECT 1 FROM emb_vecs v WHERE v.hash = c.hash AND v.model = $(q "$EMB_MODEL"))),
                   ifnull((SELECT datetime(value, 'unixepoch', 'localtime') FROM meta WHERE key = 'indexed_at'), 'never');" 2>/dev/null)
        local nf nc nv when
        IFS="$TAB" read -r nf nc nv when <<< "$row"
        say "files:    ${nf:-0} indexed, in ${nc:-0} pieces ($(du -h "$DB" | cut -f1) on disk)"
        say "last run: ${when:-never}"
        say "meaning:  ${nv:-0} of ${nc:-0} pieces have a vector (model $EMB_MODEL)"
    else
        say "files:    nothing indexed yet (rseek index)"
    fi
    if [ "$MEANING" = off ]; then
        say "ollama:   not used (meaning = off)"
    elif emb_ready "$EMB_URL" "$EMB_MODEL"; then
        say "ollama:   ready, model $EMB_MODEL answers"
    else
        say "ollama:   not ready (no answer for model $EMB_MODEL at $EMB_URL); word search works without it"
    fi
    if [ -n "$RSEEK_VEC" ]; then say "speed:    fast vector helper in use"; else say "speed:    plain SQL vector compare (rseek-vec helper not installed)"; fi
    if command -v systemctl >/dev/null 2>&1 && [ -z "${RSEEK_NO_SYSTEMD:-}" ]; then
        if systemctl --user is-enabled ruggi-seek-index.timer >/dev/null 2>&1; then
            say "timer:    on ($(systemctl --user show ruggi-seek-index.timer -p NextElapseUSecRealtime --value 2>/dev/null | sed 's/^$/next run not scheduled/'))"
        else
            say "timer:    off (index by hand with: rseek index)"
        fi
    fi
}

# ---------- rseek config ----------
cmd_config() {
    cfg_init
    local sub=${1:-show}; [ $# -gt 0 ] && shift
    case $sub in
        show)
            say "# $CONF"
            grep -v '^[[:space:]]*\(#.*\)\?$' "$CONF" || true;;
        path) say "$CONF";;
        model) load_settings; say "$EMB_MODEL";;   # the model in use (what "auto" picked)
        edit) "${VISUAL:-${EDITOR:-xdg-open}}" "$CONF";;
        add)
            [ $# -ge 1 ] || die "config add needs a folder"
            local d; d=$(expand_dir "$1")
            [ -d "$d" ] || die "not a folder: $d"
            if cfg_folders | grep -Fxq "$d"; then say "already there: $d"; return 0; fi
            printf 'folder = %s\n' "$d" >> "$CONF"
            say "added: $d   (now run: rseek index)";;
        remove|rm)
            [ $# -ge 1 ] || die "config remove needs a folder"
            local d tmpf found=0 line val; d=$(expand_dir "$1"); tmpf=$(mktemp)
            while IFS= read -r line || [ -n "$line" ]; do
                case $line in
                    folder*=*|[[:space:]]*folder*=*)
                        val=$(printf '%s' "$line" | sed 's/^[[:space:]]*folder[[:space:]]*=[[:space:]]*//; s/[[:space:]]*$//')
                        if [ "$(expand_dir "$val")" = "$d" ]; then found=1; continue; fi;;
                esac
                printf '%s\n' "$line"
            done < "$CONF" > "$tmpf"
            cat "$tmpf" > "$CONF"; rm -f "$tmpf"
            if [ "$found" = 1 ]; then say "removed: $d   (its files leave the index at the next: rseek index)"
            else die "not in the settings: $d"; fi;;
        set)
            [ $# -ge 2 ] || die "config set needs a key and a value"
            local key=$1 val=$2
            case $key in
                meaning)     case $val in on|off) ;; *) die "meaning is on or off";; esac;;
                mode)        case $val in both|words|meaning) ;; *) die "mode is both, words or meaning";; esac;;
                hidden)      case $val in yes|no) ;; *) die "hidden is yes or no";; esac;;
                limit|max_file_kb|max_doc_mb) case $val in ''|*[!0-9]*) die "$key needs a whole number";; esac;;
                min_score)   case $val in auto) ;; ''|*[!0-9.]*) die "min_score is auto or a number from 0 to 1";; esac;;
                embed_model) rm -f "$LANG_FILE";;   # "auto" picks again
                embed_url|embed_model_en|embed_model_multi|extensions|skip_folders) ;;
                folder)      die "use: rseek config add DIR";;
                *)           die "unknown setting: $key";;
            esac
            if grep -q "^[[:space:]]*$key[[:space:]]*=" "$CONF"; then
                local tmpf; tmpf=$(mktemp)
                awk -v k="$key" -v v="$val" '
                    $0 ~ "^[[:space:]]*" k "[[:space:]]*=" { print k " = " v; next } { print }' "$CONF" > "$tmpf"
                cat "$tmpf" > "$CONF"; rm -f "$tmpf"
            else
                printf '%s = %s\n' "$key" "$val" >> "$CONF"
            fi
            say "$key = $val";;
        *) die "config: show, add DIR, remove DIR, set KEY VALUE, model, edit, path";;
    esac
}

cmd_gui() {
    local g
    for g in "$HERE/ruggi-seek" "$HERE/../gui/bin/ruggi-seek"; do
        [ -x "$g" ] && { setsid "$g" "$@" >/dev/null 2>&1 & return 0; }
    done
    die "the results window is not installed (build it: bash gui/build.sh)"
}

cmd_help() {
    cat <<'EOF'
Ruggi Seek: find your files by words and by meaning.

  rseek "words or a question"        search (words and meaning, merged)
        --in DIR                     only inside this folder
        --words | --meaning | --both how to search this time
        --limit N                    how many results (default 20)
        --open N                     open result number N
        --tsv | --json               output for other programs

  rseek index                        read new and changed files (--rebuild starts over,
                                     --no-meaning skips the vectors, --quiet for timers)
  rseek status                       what is indexed; is meaning search ready
  rseek config                       show the settings
  rseek config add DIR               index this folder too
  rseek config remove DIR            stop indexing it
  rseek config set KEY VALUE         mode, limit, min_score, meaning, embed_url, embed_model,
                                     embed_model_en, embed_model_multi, hidden, max_file_kb,
                                     max_doc_mb, extensions, skip_folders
  rseek config model                 the embedding model in use (embed_model = auto picks
                                     by the languages of this computer)
  rseek config edit                  open the settings file
  rseek gui [--in DIR] [words]       the results window

Each result says why it was found: [words], [meaning] or [words+meaning]; a meaning match
also shows how similar it is (0 to 1).
EOF
}

case ${1:-help} in
    index)   shift; cmd_index "$@";;
    status)  shift; cmd_status "$@";;
    config)  shift; cmd_config "$@";;
    gui)     shift; cmd_gui "$@";;
    search)  shift; cmd_search "$@";;
    help|--help|-h) cmd_help;;
    version|--version|-V) say "rseek $VERSION";;
    *)       cmd_search "$@";;
esac
