# keepass_search
# --------------
# Busca entries en el KeePassXC database por substring (en title, username, url, notes).
# Devuelve un array JSON de paths que matchean.
#
# REQUIERE:
#   - keepassxc-cli instalado
#   - jq instalado
#   - KEEPASS_DB (env): ruta absoluta al .kdbx
#   - master password en pass o env KEEPASS_PASSWORD
#
# USO (sourced):
#   source keepass_search.sh
#   matches=$(keepass_search "github")
#   echo "$matches" | jq .

keepass_search() {
    local term="$1"

    if [ -z "$term" ]; then
        echo "keepass_search: se requiere termino de busqueda" >&2
        return 1
    fi

    local db="${KEEPASS_DB:-}"
    if [ -z "$db" ] || [ ! -f "$db" ]; then
        echo "keepass_search: KEEPASS_DB no valida: $db" >&2
        return 1
    fi

    local master
    if [ -n "${KEEPASS_PASSWORD:-}" ]; then
        master="$KEEPASS_PASSWORD"
    else
        master=$(pass show "${KEEPASS_MASTER_ENTRY:-meta/keepassxc-master}" 2>/dev/null | head -n1)
        if [ -z "$master" ]; then
            echo "keepass_search: no master pass" >&2
            return 1
        fi
    fi

    local out
    out=$(printf '%s\n' "$master" | keepassxc-cli locate -q "$db" "$term" 2>/dev/null)
    if [ $? -ne 0 ]; then
        echo "keepass_search: keepassxc-cli locate fallo" >&2
        return 1
    fi

    printf '%s\n' "$out" | grep -v '^$' | sed 's|^/||' | jq -R . | jq -s .
}
